Search code examples
prologunificationprolog-findall

Finding all unifications in prolog


I wrote my first simple code in PROLOG:

is_beginning([], _).
is_beginning([FirstLetterB|RestWordB], [FirstLetterW|RestWordW]) :-
   FirstLetterB == FirstLetterW,
   is_beginning(RestWordB, RestWordW).

It is designed to find out if first argument of is_beginning is equal to the second one beginning. Well, IMHO it can answer questions quite well, but now i wonder if there is any possibility of getting all possible answers for defined second argument. eg. for

is_beginning(Answers, [a,b,c]);

i wish to get [], [a], [a,b], [a,b,c] as Answers unification, but I am getting only [] (simplest answer).

Is there any possibility of getting what I want? Maybe there is something wrong in my definition? I already tried to use findall and forall, but it doesn't work to well for me :(

Thanks for all answers.


Solution

  • you are using (==)/2 when non needed (note the comment at end of documentation page). Indeed, if you change it to 'simple' unification (=)/2 your program works as you expect:

    is_beginning([], _).
    is_beginning([FirstLetterB|RestWordB], [FirstLetterW|RestWordW]) :-
        FirstLetterB = FirstLetterW,
        is_beginning(RestWordB, RestWordW).
    

    test:

    ?- is_beginning(Answers, [a,b,c]).
    Answers = [] ;
    Answers = [a] ;
    Answers = [a, b] ;
    Answers = [a, b, c] ;
    false.