1

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.

Yester
  • 652
  • 6
  • 18
  • 2
    By the way, you can simplify your second rule a bit. Instead of explicitly writing the equality constraint, you can do it implicitly by reusing the same variable: `is_beginning([X|A],[X|B]):-is_beginning(A,B).` – Nick Barnes Dec 10 '12 at 11:26

2 Answers2

2

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.
CapelliC
  • 59,646
  • 5
  • 47
  • 90
1

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]].
Nick Barnes
  • 19,816
  • 3
  • 51
  • 63
  • Thanks for your answer, but i already tried both of your solution. It looks like interpreter returns only one answer, but I'm not sure why. – Yester Dec 10 '12 at 11:33
  • @Yester Oops... Missed the `==` in your rule. See CapelliC's answer. – Nick Barnes Dec 10 '12 at 12:55