Reputation: 924
Prolog, recursive function: i want it to print the C with each element of the list for example: C=30 and [H|T]= [-9,-10,-30]
myfunc(C,[H|T]):-
(\+([H|T]=[])),
write(C), write(' with '), write(H), nl,
myfunc(C,T).
i check at the beginning that the head of the list is not empty. it gives me this output
30 with -9
30 with -10
30 with -30
(32 ms) no
this output is what i want but i dont want to get a 'no' at the end because this makes the parent function to fail as well! how can i remove it and put a 'yes' instead?
Upvotes: 1
Views: 151
Reputation: 5645
If you have maplist in your Prolog, you can write
myfunc(N, L) :-
maplist(my_write(N), L).
my_write(N, Val) :-
format('~w with ~w~n', [N, Val]).
With SWI-Prolog and module lambda
:- use_module(library(lambda)).
myfunc(N, L) :-
maplist(\X^format('~w with ~w~n', [N, X]), L).
Upvotes: 2
Reputation: 3180
Simple way: just add a base case with the empty list.
myfunc(_, []) :- !.
myfunc(C,[H|T]):-
write(C), write(' with '), write(H), nl,
myfunc(C,T).
test:
?- myfunc(30, [1, 2, 3]).
30 with 1
30 with 2
30 with 3
true.
I don't know if this is the best way to do that, but you didn't give us much details about your whole program, so I opted for a small modification of your predicate.
Upvotes: 3