0

Lately I have been learning Prolog and tried to write a program to count down from a number to another given number using recursion but it seems to be not working, the code is as follows:

count_down(L, L) :- !.
count_down(L, H) :-
    write(H), nl,
    Y is H-1,
    count_down(L, Y).

the first rule count_down(L, L) :- !. is to terminate the loop when counting reaches L.

repeat
  • 18,496
  • 4
  • 54
  • 166
  • 2
    What is not working? Please provide a query with real output, and expected output. – Willem Van Onsem Oct 05 '17 at 10:25
  • So how is this supposed to work? `count_down(L, H)` counts down from `H` to `L`? One big problem is: what happens if `H` is less than `L`? – lurker Oct 05 '17 at 12:58
  • `count_down(3,7).` displays `7\n6\n5\n4`, so I'm not sure why you think it does not work? – Fatalize Oct 05 '17 at 13:40
  • 2
    @Fatalize `count_down(7, 3)`, however, will not terminate before overflowing the stack. SURAJ, get rid of the cut (have `count_down(L, L).` and add a constraint to your main predicate, `count_down(L, H) :- H > L, ...`. That properly defines the predicate constraints. – lurker Oct 05 '17 at 14:08
  • Well I kind of answered my own question, when i was trying the code i was not using count_down(L,L):-!. to terminate the recursion which gave an error. And L is a low number and H is a high number so every time H > L – Suraj Maurya Oct 05 '17 at 17:49
  • Just to be anal, the cut doesn't do anything for recursion, it just cuts off other possibilities and prevents backtracking. You can think of it as a commitment operator: it commits you to the branch you're on and stops Prolog from backing up to what came before it. But only you can stop recursion from happening. – Daniel Lyons Oct 05 '17 at 19:51

0 Answers0