Reputation: 8648
I tried something like this: said path = [[1,2],[2,3],[3,4],[5,6]]
first_three(N,[H|T],[H|_]):- not(N=0),N is N-1, first_three(N,T,L).
then I call first_three(3, path, Y) but it return no.
Upvotes: 1
Views: 1082
Reputation: 15807
First of all, N is N - 1
can't possibly succeed - N
is not a variable in the imperative programming language sense, so you don't store values in it, it can be assigned only once, so to speak - so you may want to introduce a new variable and call something like N1 is N - 1
, and subsequently use N1
in the recursive call to first_three
. Then, the last argument to that recursive call comes out of nowhere, so you may need to pay attention to it too. As a last suggestion, try to split the predicate in two clauses: the first to manage the elementary basic case where N
is 0
, the second to manage the meaty cases, building on top of the other.
Oh, and since N
is a variable quantity, I would suggest to use a different name rather than the misleading first_three
for your predicate.
Upvotes: 1
Reputation: 22585
You need to add a base case (when N = 0). And you also need to instantiate a new fresh variable to assign the predecesor of N, and finally you also need to return the result of the recursion (the [H|L] in the head of the clasuse):
first_three(0,_,[).
first_three(N,[H|T],[H|L]):-
N\=0,
N1 is N-1,
first_three(N,T,L).
Of course, you can also just write something like this:
first_three([One,Two, Three|_], [One,Two, Three]).
and call it:
first_three(Path, Y).
Upvotes: 1