Using maplist with a lambda that does not have a body?
Asked Answered
G

1

6

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!

Gilliette answered 12/6, 2021 at 7:25 Comment(1)
perfect tagging! :)Demonstrable
A
4

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.

Aft answered 12/6, 2021 at 7:31 Comment(3)
This is indeed the recommended programming idiom for this case.Pitapat
As you probably know, Swiss knifes are no longer permitted on planes. And also findall/3 produces incorrect results in the airy heights of reduced instantiations and constraints alike. maplist/2.. does not have this problem. It might not terminate which certainly isn't the best. But at least it does not produce incorrect results.Decapitate
@false: yes, I'm aware of some of these problems. Thought that 'poor man' tool was a fair recap of them :)Aft

© 2022 - 2024 — McMap. All rights reserved.