Hello there, prolog newbie here!
Simple question, probably with a simple answer:
How do I use an operation on every element of a list?
For example:
Lets say I have a predicate adding 4 to the given variable:
plusFour(X,Y) :- Y is X+4.
And now I want to use that on the list [1,2,3], so that it outputs [4,5,6].
How exactly would I do that?
Thanks in advance!
1 ?- [user].
|: plusFour(X,Y) :- Y is X+4.
|:
% user://1 compiled 0.00 sec, 1 clauses
true.
2 ?- maplist(plusFour, [1,2,3,4], Z).
Z = [5, 6, 7, 8].
Is there a way to do it without a predefined predicate (i.e. maplist)?
You can even generalize it to plusN
:
?- assert(plusN(N, X, Y) :- Y is X + N).
true.
?- maplist(plusN(4), [1,2,3,4], Z).
Z = [5, 6, 7, 8].
I think you’re looking for library(yall). It’s autoloaded, so you don’t need to explicitly load it (by use_module or :- [library(yall)]). That is:
?- Xs=[1,2,3],N=4,maplist({N}/[X,Y]>>(Y is X+N),Xs,Ys).
...
Ys = [5, 6, 7].
3 Likes