Modifying prolog code to generate a list of lists

63 Views Asked by At

I have this Prolog code that generates a list of the Fibonacci numbers up to N. Giving for example

?- fib(L, 3)
   L=[0,1,1,2]

% Define the Fibonacci sequence

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

% DCG rules to generate the Fibonacci sequence list
fib_list(0) --> [0].
fib_list(N) -->
    { N >= 1,
      N1 is N - 1 },
    fib_list(N1),
    { fibb(N, Fn) },
    [Fn].

fib(L, N) :-
    phrase(fib_list(N), L).

But I want it to output a list of lists, giving;

?- fib(L,3)
   L = [0]
   L = [0,1]
   L = [0,1,1]
   L = [0,1,1,2]
   false

and also to deal with the null set:

?- fib(L,[])
   L = [0]
   L = [0,1]
   ...

I thought I could add a recursive predicate to count down from N and produce the lists, but it still only generated the final list.

1

There are 1 best solutions below

0
NaveenKumarReddy Karnapu On

You can use the below DCG which will generate the fibonacci series upto N as well as it also deals when input is [].

% When input is []
fib(List, []) :- !,
    between(0, inf, Ind),
    phrase(fibonacci(Ind, List), []).

% When input is upto N 
fib(L, N) :- 
    between(0, N, Ind),
    phrase(fibonacci(Ind, L), []).

fibonacci(0, [0]) --> [].
fibonacci(1, [0, 1]) --> [].
fibonacci(N, L) -->
    { N >= 2,  A is N - 1, B is N - 2 },
    fibonacci(A, C),
    {last(C, L1)},
    fibonacci(B, D),
    {last(D, L2)},
    { L3 is L1 + L2 , append(C, [L3], L)}.