You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python实现Haskell风格的广义斐波那契递归惰性列表?

用Python极简实现广义斐波那契数列(无类/对象)

对应Haskell中一行实现的广义斐波那契数列逻辑:

gfib f xs = (head xs) : gfib f ((tail xs) ++ [f xs])

核心实现(生成器版,无类/对象)

def gfib(f, xs):
    while True:
        yield xs[0]
        xs = xs[1:] + [f(xs)]

测试示例

借助itertools.islice可以方便地取前N个元素:

from itertools import islice

# 对应Haskell示例1:gfib sum [0,0,1] 取前10项
print(list(islice(gfib(sum, [0, 0, 1]), 10)))
# 输出: [0, 0, 1, 1, 2, 4, 7, 13, 24, 44]

# 对应Haskell示例2:gfib sum [0,1] 取前10项
print(list(islice(gfib(sum, [0, 1]), 10)))
# 输出: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

一行简化版(递归式,注意栈限制)

如果追求极致代码长度,也可以用递归lambda实现,但递归深度有限制(取太多元素会触发栈溢出):

gfib = lambda f, xs: (xs[0], *gfib(f, xs[1:]+[f(xs)]))

# 取前10项
print(gfib(sum, [0,0,1])[:10])

内容的提问来源于stack exchange,提问作者Gong-Yi Liao

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 06:45:33