ERROR: Unhandled exception: from local stack - Prolog

I tried to write a simple version length/3in Prolog.

If you look at the standard implementation length/2, it is something like below:

length([], 0).
length([Head|Tail], N) :-
    length(Tail, N1),
    N is 1+N1.

While my code uses almost the same idea, but I get the error “from the local stack”, and I think this is due to deep recursion. I could not understand why. And my code is:

mylength(_, [], 0).
mylength([H1|T1], [H1copy|T1copy], N) :-
    mylength([H1|T1], [T1copy], N1),
    N is N1 + 1.
+4
source share
1 answer

The predicate mylength/3has the following problem. I assume that you want to run it using mode mylength(+,-,-). Just then if the first argument is not canceled.

- , [H1|T1] , , /2. , [T1copy] .

, , H1copy. Prolog.

Bye

P.S.: , - , . H1copy.

, , SWI-Prolog, , SWI-Prolog . ^ C g :

Welcome to SWI-Prolog (Multi-threaded, 64 bits, Version 7.1.16)
Copyright (c) 1990-2014 University of Amsterdam, VU Amsterdam

Action (h for help) ? goals

[552,959] mylength([1, 2, 3], [[]], _G40)
[552,958] mylength('<garbage_collected>', '<garbage_collected>', _G40)
[552,957] mylength('<garbage_collected>', '<garbage_collected>', _G40)
[552,956] mylength('<garbage_collected>', '<garbage_collected>', _G40)
[552,955] mylength('<garbage_collected>', '<garbage_collected>', _G40)

, , Prolog 552959, .. !

SWI-Prolog: ERROR: Out of local stack.

+1

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


All Articles