How would you (re)implement iterate in Haskell?

前端 未结 2 1682
野趣味
野趣味 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:23

    Also note that you can find concise definitions for the range of basic Haskell functions in the report's Standard Prelude.

    Reading through this list of straightforward definitions that essentially bootstrap a rich library out of raw primitives can be very educational and eye-opening in terms of providing a window onto the "haskell way".

    I remember a very early aha moment on reading: data Bool = False | True.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题