Haskell中的斐波那契列表

问题描述 投票:-3回答:1

定义函数fibList :: Int -> [Int],该函数接收(正)数字n,并返回第一个n斐波纳契数的列表。例如,fibList 10必须返回[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

list haskell fibonacci
1个回答
-2
投票

也许使用辅助递归函数?

Prelude> fibList2 a b = a : fibList2 b (a+b)
Prelude> fibList nn = take nn (fibList2 1 1)
Prelude> 
Prelude> fibList 10
[1,1,2,3,5,8,13,21,34,55]
 Prelude> 

您能不能请您:

  1. 更正标题中的错字?

  2. 提到斐波那契数列的数学定义?

谢谢!

拼写错误可能阻止了一种现成的解决方案向您跳来。

Historical and mathematical infos about the Fibonacci serie


0
投票

我们知道fib(n-2) == fib (n) - fib (n-1),因此给定斐波那契数,我们可以重建导致它的整个序列:

fibs n = [r | i <- [1..n-1], r <- go [i,n]]
  where
  go xs@(1:1:_)                 =  [xs]
  go xs@(a:b:_) | a > 0, a < b  =  go (b-a:xs)
  go _                          =  []

正在尝试,

> mapM_ print . filter (not . null) . map fibs $ [1..100]
[[1,1,2]]
[[1,1,2,3]]
[[1,1,2,3,5]]
[[1,1,2,3,5,8]]
[[1,1,2,3,5,8,13]]
[[1,1,2,3,5,8,13,21]]
[[1,1,2,3,5,8,13,21,34]]
[[1,1,2,3,5,8,13,21,34,55]]
[[1,1,2,3,5,8,13,21,34,55,89]]

现在剩下的就是找到足够长的序列。

© www.soinside.com 2019 - 2024. All rights reserved.