Search code examples
listprologmeta-predicate

maplist with parametrized predicate


Is it possible to use parametrized predicate in mapList?

For example, I would like to do following: iter by list, and for each even element (list contains only numbers) map this element to some value (this value is set by parameter of predicate).

Sample queries:

?- mapList(p(red, blue), [1,2,3,4], [red, blue, red, blue]).
true.

?- mapList(p(green, blue), [1,2,3,4], [green, blue, green, blue]).
true.

Solution

  • Yes, the predicate just get all additional parameters. After defining p/4, running your queries (once mapList has been corrected to maplist):

    ?- [user].
    p(C1,C2,N,C) :- 0 =:= N mod 2 -> C = C2 ; C = C1.
    (^D here)
    
    ?- maplist(p(red, blue), [1,2,3,4], L).
    L = [red, blue, red, blue].