Search code examples
recursionlambdaprologprolog-cut

how to prevent no in prolog?


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?


Solution

  • 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.