Cypher236
Cypher236

Reputation: 527

How would I modify my predicate to jumble my output result?

So I'm experimenting with some stuff. I have the following simple predicate:

insert([],Y,[Y]).
insert([H|T],Y,[H,Y|T]).

So this'll insert my element Y into my list. However this always puts it in the same place, which is in the middle. But say I wanted it to be more like the following:

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

should succeed four times and give the following answers:

Zs = [4, 1, 2, 3]
Zs = [1, 4, 2, 3]
Zs = [1, 2, 4, 3]
Zs = [1, 2, 3, 4]. 

How would I modify my predicate accordingly?

Upvotes: 1

Views: 48

Answers (2)

CapelliC
CapelliC

Reputation: 60034

another useful builtin, extended in SWI-Prolog to handle insertion as well as selection:

?- nth1(_,X,a,[1,2,3]).
X = [a, 1, 2, 3] ;
X = [1, a, 2, 3] ;
X = [1, 2, a, 3] ;
X = [1, 2, 3, a] ;
false.

just ignore first argument (the index itself)

Upvotes: 2

Yasel
Yasel

Reputation: 3120

If you want to find possible position of an element in a list, then you have to find all possible concatenation of this list containing the element to insert. This can be described using append/3 predicate:

insert(X,Y,Z):- append(A, B, X), append(A, [Y|B], Z).

This predicate states that exists a concatenation of two sublist that returns list X, and this two sublist concatenated with the value Y in the head of the second sublist, returns list Z.

?- insert([1,2,3], 4, Z).
Z = [4, 1, 2, 3]
Z = [1, 4, 2, 3]
Z = [1, 2, 4, 3]
Z = [1, 2, 3, 4]
false

Upvotes: 1

Related Questions