1

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?

false
  • 10,264
  • 13
  • 101
  • 209
CSawy
  • 904
  • 2
  • 14
  • 25

2 Answers2

3

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.

Haile
  • 3,120
  • 3
  • 24
  • 40
2

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).
joel76
  • 5,565
  • 1
  • 18
  • 22