Hi, I need help . I was suppose to Write a prolog program that ‘returns’ the first N Fibonacci numbers.

for an example:

fib_list_N(5, X)
 Output: X = [0, 1, 1, 2, 3]

Instead , I am getting X= [0,1,1,2,3,5] , i am lost , What could be done to make it work ? Help me.

   append_a(X, [], [X]).
append_a(X, [H|T], [H|T2]) :- append_a(X, T, T2).

    reverse_r([], []).
reverse_r([H|T], Return) :- reverse_r(T, Z), append_a(H, Z, Return).

fib(0, 0).
   fib(1, 1).
fib(N, F) :-
N > 1,
N1 is N - 1,
N2 is N - 2,
fib(N1, F1),
fib(N2, F2),
F is F1 + F2.

fib_list(0, [0]).                         
fib_list(N, [H|T]) :-
fib(N, H),
N1 is N - 1,
fib_list(N1, T).

fib_list_N(In,Return) :-fib_list(In, Z), reverse_r(Z, Return).
Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.18 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.