listrecursionprologappendarity

Produce a list of Lucas/fibonacci sequence with Prolog


I am just fiddling with prolog a little an I've come across a problem I don't know how to solve. I want to create a procedure that returns the Lucas sequence of a given number In. I have got the code to return the actual number down, but it does just that, return the Lucas value of the number In. What I want is to return a list with all the Lucas sequence numbers up to that one. I've bee trying to do it and I've just got no idea how to implement this. Below is my attempt. Any help would be appreciated!!!

lucas(0,[2]).
lucas(1,[2,1]).
lucas(In,Exit):- 
    In>1,
    First is In-1, Second is In-2, 
    lucas(First, First1),lucas(Second,Second1), 
    [Out] is First1+Second1, 
    Lucas(1,L),
    app([L],Out,Exit). 

Solution

  • An easy solution is to define the Lucas numbers and afterwards producing a list of Lucas numbers:

    % Definition of Lucas numbers according to Wikipedia
    lucas(0, 2) :- !.
    lucas(1, 1) :- !.
    lucas(N, R) :-
        N > 1,
        N_Pre is N - 1,
        N_PrePre is N - 2,
        lucas(N_Pre, LHS),
        lucas(N_PrePre, RHS),
        R is LHS + RHS.
    
    % Memoization of Lucas numbers
    :- table lucas/2.
    
    % Generate List
    seq(M, Result) :-
        numlist(0, M, List),
        maplist(lucas, List, Result).
    

    If I then call, seq, it produces a sequence of Lucas numbers:

    ?- seq(5, R).
    R = [2, 1, 3, 4, 7, 11].