user41580
user41580

Reputation: 23

3 consecutive elements in Prolog using concat

So I am working on this problem to have 3 X elements to be consecutive in a list and can only use concat.

Here is what I've attempted:

threeConsecutive(X, L):- concat(X, X, L2), concat(L2, X, L).

Is this correct? If not, can you please explain what I'm doing wrong? From how I see it, I'm concatenating 2 X elements and putting them in another free variable named L2 and then will concat that again with the element X. Finally I store that inside the original list L.

Would greatly appreciate if someone could check this over as I'm really trying to grasp the concept of concat within Prolog.

Thank you!

Upvotes: 2

Views: 201

Answers (2)

user1812457
user1812457

Reputation:

All you have to do is use pattern matching:

?- append(_, [X,Y,Z|_], [a,b,c,d,e,f]).
X = a, Y = b, Z = c ;
X = b, Y = c, Z = d ;
X = c, Y = d, Z = e ;
X = d, Y = e, Z = f ;
false.

append/3 does the backtracking for you.

If you want to have the three elements in a list of their own, you can use two calls to append/3:

append(_, Suffix, List), append([X,Y,Z], _, Suffix)

As how to make a list with three elements: just say List = [X,Y,Z]. To make a list of any length you could even use length(List, Len), so for example length(List, 3).

And, if you need the three variables to be the same (as in, unify them), then just use the same variable: List = [X, X, X].

Upvotes: 2

CapelliC
CapelliC

Reputation: 60034

Is this correct?

no, the first problem being that append/3 (for sake of discussion, let's say the undefined concat/3 is append/3) states a relation among 3 lists. So

concatenating 2 X elements and putting them in another free variable named L2

should be

concat([X], [X], L2)

This could be better expressed with unification, as

[X,X] = L2

The same problem applies in

..., concat(L2, X, L).

should be concat(L2, X, L).

..., concat(L2, [X], L).

and then you can see that the whole code would reduce to

threeConsecutive(X, [X,X,X]).

So the second problem is apparent, but since @Boris answer has already shown the proper pattern required, I'll avoid to repeat it here.

Upvotes: 0

Related Questions