你将如何(重新)在Haskell中实现迭代? [英] How would you (re)implement iterate in Haskell?

查看:149
本文介绍了你将如何(重新)在Haskell中实现迭代?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  iterate ::(a  - > a) - > a  - > [a] 



<你可能知道) iterate 是一个函数,它具有函数和起始值。然后它将函数应用于起始值,然后将相同的函数应用于最后的结果,依此类推。

  Prelude>采取5 $迭代(^ 2)2 
[2,4,16,256,65536]
前奏>

结果是一个无限列表。 (这就是为什么我使用)。
我的问题你将如何在Haskell中实现你自己的 iterate'函数,仅使用基础知识((:) $ b

(Haskell初学者在这里) (++) lambdas,pattern mataching,guards等)

解决方案

好吧, iterate 构造了一个无限值列表 a f 完成。因此,我将首先编写一个函数,该函数将前缀 a 添加到通过 fa 递归调用迭代构建的列表中:

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆