你将如何(重新)在Haskell中实现迭代? [英] How would you (re)implement iterate in Haskell?
问题描述
iterate ::(a - > a) - > a - > [a]
<你可能知道) iterate
是一个函数,它具有函数和起始值。然后它将函数应用于起始值,然后将相同的函数应用于最后的结果,依此类推。
Prelude>采取5 $迭代(^ 2)2
[2,4,16,256,65536]
前奏>
结果是一个无限列表。 (这就是为什么我使用 (Haskell初学者在这里) 好吧, iterate 构造了一个无限值列表 a 由 f 完成。因此,我将首先编写一个函数,该函数将前缀 a 添加到通过 fa 递归调用迭代构建的列表中: 感谢懒惰评估,只有计算我函数值所需的构造列表的那部分才会被评估。取
)。
我的问题你将如何在Haskell中实现你自己的 iterate'
函数,仅使用基础知识((:)$ c $ ($)
$ b (++)
lambdas,pattern mataching,guards等)
iterate ::(a - > a) - > a - > [a]
迭代fa = a:iterate f(fa)
iterate :: (a -> a) -> a -> [a]
(As you probably know) iterate
is a function that takes a function and starting value. Then it applies the function to the starting value, then it applies the same function to the last result, and so on.
Prelude> take 5 $ iterate (^2) 2
[2,4,16,256,65536]
Prelude>
The result is an infinite list. (that's why I use take
).
My question how would you implement your own iterate'
function in Haskell, using only the basics ((:)
(++)
lambdas, pattern mataching, guards, etc.) ?
(Haskell beginner here)
Well, iterate constructs an infinite list of values a incremented by f. So I would start by writing a function that prepended some value a to the list constructed by recursively calling iterate with f a:
iterate :: (a -> a) -> a -> [a]
iterate f a = a : iterate f (f a)
Thanks to lazy evaluation, only that portion of the constructed list necessary to compute the value of my function will be evaluated.
这篇关于你将如何(重新)在Haskell中实现迭代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!