Search code examples
scalahaskellfunction-composition

Idiomatic Haskell-like iterate in Scala?


In Haskell, I can get an infinite list of sequential function applications by calling:

iterate :: (A -> A) -> A -> [A]

Suppose in scala I have f(x: A): A. Is there a function that will result in a stream of sequential function applications? Like iter(f: A => A, x: A): Stream[A]?


Solution

  • Yes, it's in the library already: Iterator.iterate

    Iterator.iterate(1)(_ + 1).drop(100 * 100 * 100).take(10).toList
    //> List(1000001, 1000002, 1000003, 1000004, 1000005,
             1000006, 1000007, 1000008, 1000009, 1000010)