简体   繁体   English

使用 Prolog 生成 Lucas/fibonacci 序列列表

[英]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.我只是稍微摆弄一下 prolog,我遇到了一个我不知道如何解决的问题。 I want to create a procedure that returns the Lucas sequence of a given number In.我想创建一个返回给定数字 In 的Lucas 序列的过程。 I have got the code to return the actual number down, but it does just that, return the Lucas value of the number In.我有返回实际数字的代码,但它就是这样做的,返回数字 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). 

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,它会生成一个卢卡斯数序列:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM