Haise Sasaki
Haise Sasaki

Reputation: 329

Subtract 1 from number (recursion in Prolog)

I'm trying to understand how to write recursive functions in Prolog. I've come with a the following code:

reduceBy1(Input,Output) :-
    (Input > 0 -> Output is Input - 1). 

calling reduceBy1(10,Output). results in 9. So far, so good. But how do I pass Output back into reducyBy1\2 ?

Upvotes: 0

Views: 417

Answers (1)

Reema Q Khan
Reema Q Khan

Reputation: 878

Here is a way:

reduceBy1(0,[]).
reduceBy1(H,[H|T]) :-
         (H>0-> 
         H1 is H-1,
         reduceBy1(H1,T)).

Suppose you give a number as input, now you want it to print all the numbers in descending order. The Output list should end at 1.

The first predicate is the base case: It says that when Input which is H in our case is 0 and whatever is in the list, the program should stop. Base predicate is the predicate with the ending condition. For the next predicate we take H as input and [H|T] as Output meaning start the output with the input number, that is why [H|T]. It then checks if Input is greater than 0 it should then subtract 1 and save it to H1. Now we give reduceBy1 new values H1 which becomes the new input , T is the output that starts storing the numbers as a list. The program goes through each predicate to see which one is a success. If the input is =0 [This will happen when the numbers keep getting decremented till we reach that situation], so when it checks the base predicate it is a success. The program ends by giving whatever is stored in the List at that point.

?-reduceBy1(6,L).
L = [6, 5, 4, 3, 2, 1]

?-reduceBy1(10,L).
L = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

?-reduceBy1(-5,L).
False

Upvotes: 1

Related Questions