konopoly
konopoly

Reputation: 155

Take a positive integer n and produce a list that prints out a list in prolog?

I am trying to write a prolog rule to take a positive integer n and gives back a list that counts down from n to 0, including negatives. So spiralDown(4,L) would return L=[4,-4,3,-3,2,-2,1,-1,0]. I got it to return the positive values but cant get it to return the negative values.

ruleOne(-1,[]).
ruleOne(X,[H|T]) :-
     Y is X-1,
     H=X,
     ruleOne(Y,T).

Upvotes: 1

Views: 193

Answers (2)

Nicholas Carey
Nicholas Carey

Reputation: 74287

Here's one solution:

spiral_down(Hi,Ns) :-
  integer(Hi) ,
  Hi >= 0 ,
  Lo is -Hi ,
  spiral_down(Hi,Lo,Ns)
  .

spiral_down( Hi , Hi , [Hi]    ) .
spiral_down( Hi , Lo , [Hi|Ns] ) :-
  Hi > Lo ,
  H1 is Hi-1 ,
  spiral(H1,Lo,Ns)
  .

And another:

spiral_down( 0 , [] ) .
spiral_down( M , [M,N|Xs]) :-
  M > 0 ,
  N is -M ,
  M1 is M-1 ,
  spiral_down( M1 , Xs )
  .

Upvotes: 0

user1812457
user1812457

Reputation:

This is an attempt at a solution that has deficiencies, but it would point you in the correct direction, I hope:

spiral_down(N, [N, Minus_N|Rest]) :-
    succ(N0, N),
    Minus_N is -N,
    spiral_down(N0, Rest).
spiral_down(0, [0]).

Upvotes: 1

Related Questions