我想做的是定义一个像这样的函数:
[f 0, f f 0, f f f 0, f f f f 0, f f f f f 0..]
换句话说,每个元素是通过函数运行的最后一个元素。
我已经尝试过几次,以通过调用预定义了前几个元素的列表的方式,使它以类似于我在Haskell中看到的斐波那契数列的方式工作:
fib = 0 : 1 : zipWith (+) fib (tail fib)
ls = 0 : f 0 : f (last ls)
如果我将f定义为一个简单的addOne函数,例如:
f =(+1)
我收到此错误:
<interactive>:124:5: error:
* Occurs check: cannot construct the infinite type: a ~ [a]
Expected type: [[a]]
Actual type: [a]
* In the expression: 0 : (f 0) : f (last y)
In an equation for `y': y = 0 : (f 0) : f (last y)
* Relevant bindings include
y :: [[a]] (bound at <interactive>:124:1)
如何创建功能类似的列表?
最佳答案
如果您想自己定义它,而不是使用@WillemVanOnsem指出的迭代,那么简单的原始递归就是您的 friend :
f :: (a -> a) -> a -> [a]
f g x = let new = g x in new `seq` new : f g new
这与iterate相似,除了iterate从您提供的元素(第一个
x
)而不是函数的第一个应用程序开始:iterate :: (a -> a) -> a -> [a]
iterate f x = x : iterate f (f x)
hoogling可以获取针对此类功能的自我教育,并读取基本包中找到的所有搜索命中的implementation。
关于list - 如何在Haskell中定义对函数的递归调用列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57185779/