Human
Human

Reputation: 47

Force to backtrack in Prolog

I want to code a prefix function with prolog, but it does not work.

Here's my code:

prefix(P,[X|_]) :-
    P == X.

And I want that this input results to true:

?- prefix([1,2],[1,2,3,4]).

The problem is that I want that the X goes back and tries to get another value to result to true.

Can you show me where the mistake is?

Upvotes: 2

Views: 1171

Answers (3)

repeat
repeat

Reputation: 18726

Here's my advice:

  • Explore and use tried-and-tested library predicates: don't reinventing the wheel!

  • Read the Prolog prologue for precise definitions of these commonly used predicates: member/2, append/3, length/2, between/3, select/3, succ/2, maplist/2..8.

  • Try to not use meta-logical Prolog facilities—like (==)/2—if you don't have to.

  • As a beginner, particularly focus on the pure monotonic subset of Prolog.

End of preaching:)


Let's get back to the question! Based on append/3 we can define prefix_of/2 like this:

prefix_of(Prefix,List) :- 
   append(Prefix,_Suffix,List).

Sample queries:

?- prefix_of([1,2],[1,2,3,4]).
true.

?- prefix_of(Prefix,[1,2,3,4]).
  Prefix = []
; Prefix = [1]
; Prefix = [1,2]
; Prefix = [1,2,3]
; Prefix = [1,2,3,4]
; false.

Upvotes: 3

CapelliC
CapelliC

Reputation: 60014

P is a list, while X is an element. So, some 'deep' change to your code is required. Maybe

prefix([X|Ps], [X|Qs]) :- prefix(Ps, Qs).
prefix([], _).

Upvotes: 2

Michel Billaud
Michel Billaud

Reputation: 1826

By your définition, prefix([1,2],[1,2,3,4]) is equivalent to [1,2] == 1, which obviously fails.

What you probably want is the equivalence with prefix([2], [2,3,4])

Upvotes: 1

Related Questions