在Haskell中实现迭代

在Haskell中实现迭代

本文介绍了你将如何(重新)在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中实现迭代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 08:18