Insert prologue at any position

New in Prolog, trying to write a predicate to provide all the options that an element can be inserted into the list at any position. Example:

ins ins(a, [b,c], R).should indicate:

R = [a,b,c]
R = [b,a,c]
R = [b,c,a]

which he does, but then gives the error "Out of Global stack". Is there a way to make it more deterministic, give results and do it? When it starts in the opposite direction, i.e. ins (X, Y, [a, b, c]). It gives the expected results, and then says false, indicating that it has completed. The code:

app([],L,L).
app([H|T],L2,[H|L]) :- 
    app(T,L2,L).

ins(E, List, R) :-
    R = R1,
    app(R2, R3, R1),
    app([E], R4, R3),
    app(R2, R4, List).

Here is the link to run the code in the online compiler, SWISH (This is also an example of how I hope to use ins, but ins are a problem right now) Any help would be appreciated!

+4
source share
3

, ? -, Prolog , , : Buy. . . !

, ? - ?

, Prolog . false :

?- ins(a, [b,c], R), false.
ERROR: Out of global stack

, : false, . failure-slice

app([],L,L) :- false.
app([H|T],L2,[H|L]) :-
    app(T,L2,L), false.

ins(E, List, R) :-
    R = R1,
    app(R2, R3, R1), false,
    app([E], R4, R3),
    app(R2, R4, List).

?- ins(a, [b,c], R), false.

, - , . : , — !

, , .

/3- .


- : , . , . , [A] app/3. app/3.

+3

:

ins(X, [], [X]).
ins(X, [H|T], [X,H|T]).
ins(X, [H|T], [H|T2]) :-
    ins(X, T, T2).

, :

?- ins(a, [b,c], R).
R = [a, b, c] ;
R = [b, a, c] ;
R = [b, c, a] ;
false.

?- ins(a, L, [a,b,c]).
L = [b, c] ;
false.

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

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

?- ins(a, X, Y).
X = [],
Y = [a] ;
X = [_5312|_5314],
Y = [a, _5312|_5314] ;
X = [_5312],
Y = [_5312, a] ;
X = [_5312, _5324|_5326],
Y = [_5312, a, _5324|_5326] ;
+1

Prolog , select:

?- select(a, Out, [b,c]).
Out = [a, b, c] ;
Out = [b, a, c] ;
Out = [b, c, a] ;
false.

You can use it with another very useful predicate called setof :

ins(Elem, In, Lst_Out) :-
    setof(Out, select(Elem, Out, In), Lst_Out).

This gives:

?- ins(a, [b,c], Out).
Out = [[a, b, c], [b, a, c], [b, c, a]].
0
source

Source: https://habr.com/ru/post/1689540/


All Articles