How do you write a Prolog procedure map(List, PredName, Result)
that applies the predicate PredName(Arg, Res)
to the elements of List
, and returns the result in the list Result
?
For example:
test(N,R) :- R is N*N.
?- map([3,5,-2], test, L).
L = [9,25,4] ;
no
This is usually called
maplist/3
and is part of the Prolog prologue. Note the different argument order!The different argument order permits you to easily nest several
maplist
-goals.maplist
comes in different arities and corresponds to the following constructs in functional languages, but requires that all lists are of same length. Note that Prolog does not have the asymmetry betweenzip
/zipWith
andunzip
. A goalmaplist(C_3, Xs, Ys, Zs)
subsumes both and even offers more general uses.maplist/2
corresponds toall
maplist/3
corresponds tomap
maplist/4
corresponds tozipWith
but alsounzip
maplist/5
corresponds tozipWith3
andunzip3