4meta5 / reconocer

recognize relations from integer sequences
MIT License
0 stars 0 forks source link

infinite recursion in arithmetic and geometric seq #6

Closed 4meta5 closed 3 years ago

4meta5 commented 3 years ago

This is a problem with arithmetic which bleeds into other code. Why doesn't this fail earlier? Some infinite recursion here, but I'd like it to fail the first time that the difference sequence is shown to not be constant....

arithmetic([X,Y],Q) :-
    Q is Y-X.
arithmetic([X,Y|T],Q) :-
    arithmetic([X,Y],Q),
    arithmetic([Y|T],Q).

QUERY:

?- arithmetic([1,4,16,64],Q).
ERROR: Stack limit (1.0Gb) exceeded
ERROR:   Stack sizes: local: 0.5Gb, global: 0.2Gb, trail: 5Kb
ERROR:   Stack depth: 5,162,016, last-call: 0%, Choice points: 3
ERROR:   In:
ERROR:     [5,162,016] user:arithmetic([length:2], 3)
ERROR:     [5,162,015] user:arithmetic([length:2], 3)
ERROR:     [5,162,014] user:arithmetic([length:2], 3)
ERROR:     [5,162,013] user:arithmetic([length:2], 3)
ERROR:     [5,162,012] user:arithmetic([length:2], 3)
ERROR: 
ERROR: Use the --stack_limit=size[KMG] command line option or
ERROR: ?- set_prolog_flag(stack_limit, 2_147_483_648). to double the limit.

Originally posted by @4meta5 in https://github.com/4meta5/reconocer/issues/1#issuecomment-727739994

4meta5 commented 3 years ago

just fixed it by adding constraint length(T,Z),Z>0 so the code is now

arithmetic([X,Y],Q) :-
    Q is Y-X.
arithmetic([X,Y|T],Q) :-
    length(T,Z),Z>0,
    arithmetic([X,Y],Q),
    arithmetic([Y|T],Q).

geometric([X,Y],Q) :-
    Q is Y/X.
geometric([X,Y|T],Q) :-
    length(T,Z),Z>0,
    geometric([X,Y],Q),
    geometric([Y|T],Q).