Can fold be used to create infinite lists?

前端 未结 4 1157
执笔经年
执笔经年 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:18

    You can use zipWith to write your definition

    fibonacci = 1:1:zipWith (+) fibonacci (tail fibonacci)
    

    edit: Ok, I dont think you can use foldl or foldr to create infinite list. Not in any simple imaginable sense. If you look at the simple definition of foldl

    foldl f z []     = z
    foldl f z (x:xs) = foldl f (f z x) xs
    

    foldl never returns until it has exhausted the whole list. So a simple example like

    g = foldl f [] [1..]
     where 
      f xs a = xs ++ [a]
    
    > take 10 g
    

    will not work even and it will loop on forever.

提交回复
热议问题