"Fuera de la pila local" invirtiendo una lista

I wrote the following Prolog code:

concatenate([X|L1], L2, [X|L3]) :- concatenate(L1, L2, L3).
concatenate([], L, L).

rev([X|L], Y) :- concatenate(Z, [X], Y), rev(L, Z).
rev([], []).

If I do some queries like:

?- rev([1,2,3], [3,2,1]).  ->  true
?- rev([1,2,3], [ X, Y, Z]).  -> X=3, Y=2, Z=1

it's ok, but if I do:

?- rev([1, 2, 3], X).

Yo obtengo:

ERROR: Out of local stack

I'm sure I can find a correct implementation of reverse function on the web, but I want to know what does cause this error.

preguntado el 28 de agosto de 12 a las 11:08

Not a solution, but you can try printing the value at each of the step to debug the problem. -

2 Respuestas

concatenate(L1, L2, L3). get called with ambas L1 and L3 not instanced, then loops forever. You can see this behaviour using the debugger: just

?- gtrace,rev([1,2,3],X).

then request a step inside concatenate (hit the space bar). In top left frame (bindings) you see the instantiated variables: just L2 get a value.

Respondido 28 ago 12, 11:08

En lugar de:

rev([X|L], Y) :- concatenate(Z, [X], Y), rev(L, Z).

Tratar:

rev([X|L], Y) :- rev(L, Z), concatenate(Z, [X], Y).

Respondido 28 ago 12, 14:08

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.