Question

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.

Was it helpful?

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.

OTHER TIPS

The interpreter won't immediately return all solutions. When it returns [], press ";" to tell it to continue searching:

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

If you need all these solutions in a Prolog list, rather than just printed out in the console, findall/3 is indeed what you're looking for:

?- findall(X, is_beginning(X, [a,b,c]), L).
L = [[], [a], [a, b], [a, b, c]].
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top