Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Result is not saving on prolog variable

Tags:

prolog

I've got the following prolog function

range(Floor, Ceil, _) :- Ceil2 is Ceil+1, range(Floor, Ceil2, [], Floor).
range(_, Ceil, L, Ceil):- write(L), !.
range(Floor, Ceil, L, Cnter):- concatenate(L, [Cnter], L2), Cnter2 is Cnter + 1, range(Floor, Ceil, L2, Cnter2).

I want to get a list o all the numbers between floor and ceil, I can get this to work but it only prints out the list it doesn't return it as a solution to the query.

Expected output would be : range(2,7,R) => R = [2,3,4,5,6,7]

instead I get range(2,7,R) => [2,3,4,5,6,7] ; true.

Where the list is only printed out as a part of the function.

I suspect Im still thinking in a iterative kind of way and this is the root of my problem.

Edit to add concatenate function

 concatenate([], L, L).
 concatenate([X|Y], L1, [X|L2]) :- concatenate(Y, L1, L2).

Solution with help from @coder

rank(Ceil, Ceil, []).
rank(Floor, Ceil, [Floor|R2]):- Floor2 is Floor + 1, range(Floor2, Ceil, R2), !.    
like image 627
Alejandro Valdes Avatar asked Dec 06 '25 22:12

Alejandro Valdes


1 Answers

You just need to change a little the range/4 predicate:

range(Floor, Ceil, R) :- Ceil2 is Ceil+1, range(Floor, Ceil2, R, Floor).
range(_, Ceil, [], Ceil).
range(Floor, Ceil, [Cnter|L], Cnter):- 
   Cnter2 is Cnter + 1, range(Floor, Ceil, L, Cnter2)
like image 147
coder Avatar answered Dec 08 '25 23:12

coder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!