Reputation: 12658
Having a list List
filled with numbers, I want to obtain a list of pairs Pairs
, where each pair in Pairs
is in the form <number>-0
, i.e., each number of List
should be followed by -0
.
I came up with following solution to this, using maplist
and a lambda:
List = [1,2,30], maplist([X,X-0]>>(!), List, Pairs).
Result: Pairs = [1-0, 2-0, 30-0].
While this works, the lambda [X,X-0]>>(!)
just looks odd to me.
I know that I could also write [X,Y]>>(Y=X-0)
to have something "useful" in the body, but I was wondering if I could write the first version without the "empty lambda body"? Or is there a way to avoid the lambda at all, without introducing a new predicate (I would like to keep the solution to one line)? Thanks!
Upvotes: 6
Views: 194
Reputation: 60034
An alternative less 'intrusive' could be
?- List = [1,2,30], maplist([X,X-0]>>true, List, Pairs).
edit
Attempting an easy answer to
is there a way to avoid the lambda at all
In my old naive interpreter, I didn't have maplist/N, since it was based on Clocksin-Mellish first book, where call/N was not introduced.
So I frequently used this pattern, based on findall/3 and member/2, to transform a list.
?- List = [1,2,30], findall(X-0,member(X,List),Pairs).
findall(Template,Goal,ResultList)
is a bit the 'swiss knife' of list processing in Prolog. Since it captures all solutions of Goal
on backtracking and copies Template
, it performs a 'poor man' garbage collection, because the proof/variables/trail stacks are reset among Goal
calls.
Upvotes: 4