Generate list of numbers from N to 1 in prologue

I am trying to generate a list of N to 1 numbers without using built-in predicates like findall or numlist. What am I doing wrong?

    pred(N,[H|T]):-  H is N, N1 is N-1, pred(N1,T).
    pred(1,[]).

      

I keep getting ERROR: from the global stack

+3


source to share


2 answers


Switch the order of your offers. Put the second sentence first, otherwise he won't be able to contribute (i.e. stop) and the first sentence continues to count down to negative infinity.



Of course, it's even better to make the two sentences mutually exclusive by adding a simple test as the first goal to your first sentence.

+1


source


The most complete solution would be:

pred(1, [1]).
pred(N, [N|T]) :-
    N > 1,
    N1 is N-1,
    pred(N1, T).

      

Without the condition, N > 1

you can still get a stack overflow:

| ?- pred(3, L).

L = [3,2,1] ? ;

Fatal Error: global Qaru (size: 32768 Kb, reached: 32765 Kb, environment variable used: GLOBALSZ)

      



But with the condition N > 1

:

| ?- pred(3, L).

L = [3,2,1] ? ;

(1 ms) no
| ?-

      

Also, given the right conditions, the order of your predicates doesn't matter anymore. This is because your suggestions only work correctly under the conditions they need to fulfill. Without it, your proposal pred(N, [N|T]) :- ...

that is only meant to work when N > 1

will also try to run when N =< 1

. Changing the order only hides this problem and only a few. However, ordering can be important to efficiency.

+2


source







All Articles