Scala中的惯用Haskell式迭代?

时间:2015-09-12 02:37:31

标签: scala haskell function-composition

在Haskell中,我可以通过调用:

获得无限的顺序函数应用程序列表
iterate :: (A -> A) -> A -> [A]

假设在scala中我有f(x: A): A。是否有一个函数会产生顺序函数应用程序流?喜欢iter(f: A => A, x: A): Stream[A]

3 个答案:

答案 0 :(得分:11)

是的,已经在图书馆:Iterator.iterate

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

答案 1 :(得分:5)

Iterator.iterateStream.iteratevia Paul's answer):

for (auto it = Records.begin(); it != Records.end(); ++it) {
    it->name = ...
    it->grade = ...
}

或者你可以自己写一个,使用Stream.iterate(1)(_ + 1)

Stream

(请注意,抓住def iter[A](f: A => A, x: A): Stream[A] = { val result = f(x) result #:: iter(f, result) } 会导致记忆问题warned about in the documentation)。使用它就像:

Stream

答案 2 :(得分:0)

基本上与@Sean Vieira相同,具有更多类似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)

交换fx的位置可以帮助编译器:

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)