3

I'm trying to implement a Scheme-like map function, i.e.

map([X1, X2, ..], Fun) ->[Fun(X1), Fun(X2), ...] 

I wrote this code:

map([], Fun, []).
map([H|T], Fun, [HO|TO]) :- call(Fun, H, HO), map(T,F,TO).

Now, looking at this run:

?- map([1,2,3], plus(1), X).
X = [2, 3, 4] ;
X = [2, 3, 4] ;
X = [2, 3, 4] ;
X = [2, 3, 4] ;
ERROR: map/3: Arguments are not sufficiently instantiated
   Exception: (9) map([3], _G380, _G351) ?
  1. How can I make it stop after the first solution provided?
  2. How can I trace it?If i use trace it stop the execution after the first solution.
2
  • SWI-Prolog version 5.10.4 for i386 Commented Aug 29, 2012 at 18:24
  • Note that SWI-Prolog has a maplist predicate that does exactly what you want. Commented Aug 29, 2012 at 20:08

1 Answer 1

6

1) the code you posted has a problem: map(T,F,T0) should be map(T,Fun,T0). without this change i get the error you mentioned immediately; with this correction it runs flawlessly. (it is also a good idea to change map([], Fun, []) to map([],_Fun,[]) since you dont use the variable Fun - you should get a warning for singleton variables)

2) when you trace it and reach the first solution, press ;. alternatively, in swi-prolog, press the spacebar instead of enter and the tracing will continue.

6 ?- trace.
true.

[trace] 6 ?- X = 1 ; X = 2.
   Call: (7) _G522=1 ? creep
   Exit: (7) 1=1 ? creep
X = 1 ;
   Call: (7) _G522=2 ? creep
   Exit: (7) 2=2 ? creep
X = 2.
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for your help. I changed F n Fun. It does not give me that error anymore, but it still gives me more than one solution (always the same, the correct one, but repeated). I really cannot understand why.
can you try this: add to the code foo(_,42). and then run map([1,2,3],foo,X). and map([1],foo,X) it's quite weird, i'm running 5.10.4 too. are you on linux? in any case you can fix it with a wrapper predicate: map_w(X,Y,Z):- once(map(X,Y,Z)).
Yep, I'm on Linux. Thank you for your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.