How would you (re)implement iterate in Haskell?

前端 未结 2 1681
野趣味
野趣味 2021-02-05 17:46
iterate :: (a -> a) -> a -> [a]

(As you probably know) iterate is a function that takes a function and starting value. Then it ap

2条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-05 18:26

    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.

提交回复
热议问题