Can fold be used to create infinite lists?

前端 未结 4 1146
执笔经年
执笔经年 2021-01-18 07:00

I have written the following code which creates an infinite list of Fibonacci numbers:

fibs = 1:1:fib 1 1
  where fib a b = a+b:fib b (a+b)

4条回答
  •  独厮守ぢ
    2021-01-18 07:23

    One way to avoid explicit recursion is to use fix to express the recursion as a fixed point.

    import Data.Function (fix)
    
    fibs = fix $ \l -> [1,1] ++ zipWith (+) l (tail l)
    

    or in point-free style

    import Data.Function (fix)
    import Control.Monad.Instances
    
    fibs = fix $ ([1,1] ++) . (zipWith (+) =<< tail)
    

提交回复
热议问题