Is the idiomatic Haskell-like repeated in Scala?

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

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

Suppose the scala has f(x: A): A. Is there a function that will lead to a stream of consecutive applications? How iter(f: A => A, x: A): Stream[A]?

+4
source share
3 answers

Yes, this is already in the library: Iterator.iterate

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

There is Iterator.iterate, and Stream.iterate( through Paul's answer ):

Stream.iterate(1)(_ + 1)

Or you can write it yourself using Stream:

def iter[A](f: A => A, x: A): Stream[A] = {
  val result = f(x)
  result #:: iter(f, result)
}

( , Stream memoization ). , :

scala> iter[Int](_ + 1, 1).iterator.drop(100 * 100 * 100).take(10).toList
res1: List[Int] = List(1000002, 1000003, 1000004, 1000005, 1000006, 1000007, 1000008, 1000009, 1000010, 1000011)
+5

Basically the same as @Sean Vieira, with more syntax like Haskell:

scala> def iterate[A]: (A => A) => A => Stream[A] = {
     |     f => x => x #:: iterate(f)(f(x))
     | }
iterate: [A]=> (A => A) => (A => Stream[A])

scala> iterate[Int](_+1)(1) take 10 toList
res1: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

And interchanged fand xcan help the compiler:

scala> def iterate[A]: A => (A => A) => Stream[A] = {
     |     x => f => x #:: iterate(f(x))(f)
     | }
iterate: [A]=> A => ((A => A) => Stream[A])

scala> iterate(1)(2+) take 10 toList //Don't need to use iterate[Int] here
res3: List[Int] = List(1, 3, 5, 7, 9, 11, 13, 15, 17, 19)
0
source

Source: https://habr.com/ru/post/1607042/


All Articles