-2

This is my prolog code, which gave me the following error:

ERROR: Out of global stack

hasA(S,A):- name(S,L1),
            compar(L1,A).
compar([H1,H2|T1],T1):- H1 == 1575, H2 == 1740.

neda(H,A):- hasA(H,Z1),
            append(A,[1575,1740],A),
            state(Z1,Z2),
            append(A,Z2,A).
state([H|T],T):- H == 32.
state(A,A).

What is wrong? Can you help me with it?

Ionic
  • 3,884
  • 1
  • 12
  • 33
Max
  • 1
  • 1
  • What ths code have to do exactly ? – Emrys Myrooin Jun 29 '15 at 10:21
  • I don't see where you have a recursion, so perhaps this isn't all of your pertinent code? You should show what query you call that causes the stack error. `append(A, [1575,1740], A)` will always fails since a list, `A`, with `[1575, 1740]` appended to it, can't give you the same list, `A` back again. Likewise, `append(A, Z2, A)` will always fail unless `Z2` is the empty list (`[]`). – lurker Jun 29 '15 at 13:14
  • @lurker: name/2 it's the obsolete version of atom_codes/2 – CapelliC Jun 29 '15 at 13:18
  • @CapelliC thank you. I'll remove that part of my comment. – lurker Jun 29 '15 at 13:18

1 Answers1

0

Assuming that you call neda(H,A) with A being a free variable you end up calling append(A,[1575,1740],A) with A being a free variable as well. However, traditionally, append is implemented as

append([],Ys,Ys).
append([X|Xs],Ys,[X|Zs]) :- append(Xs,Ys,Zs).

Unification of append(A,[1575,1740],A) with append([],Ys,Ys) fails since it requires A to be [], on the one hand, and [1575,1740], on the other hand. Hence, Prolog tries to unify append(A,[1575,1740],A) with append([X|Xs],Ys,[X|Zs]) and succeeds with {A/[X|Xs], Ys/[1575,1740], Xs/Zs} which leads to the call append(Xs,[1575,1740],Xs) and the process repeats, i.e., Prolog enters an infinite recursion and ultimately runs out of stack.

If I guess your intention correctly, you first would like to append [1575,1740] to A and then to append Z2. This would mean that you need to introduce two new variables, say A1 and A2, to record the state of A after each appending step:

neda(H,A):- hasA(H,Z1),
            append(A,[1575,1740],A1),
            state(Z1,Z2),
            append(A1,Z2,A2).

Beware, however, that with A being a free variable on backtracking this code will generate lists of increasing length; is this what you want?

Alexander Serebrenik
  • 3,567
  • 2
  • 16
  • 32