hil*_*lem 4 haskell scala function-composition
在Haskell中,我可以通过调用以获得无限的顺序函数应用程序列表:
iterate :: (A -> A) -> A -> [A]
Run Code Online (Sandbox Code Playgroud)
假设我有scala f(x: A): A
.是否有一个函数会产生顺序函数应用程序流?喜欢iter(f: A => A, x: A): Stream[A]
?
The*_*aul 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)
Run Code Online (Sandbox Code Playgroud)
有Iterator.iterate
和Stream.iterate
(通过保罗的回答):
Stream.iterate(1)(_ + 1)
Run Code Online (Sandbox Code Playgroud)
或者您可以自己编写一个,使用Stream
:
def iter[A](f: A => A, x: A): Stream[A] = {
val result = f(x)
result #:: iter(f, result)
}
Run Code Online (Sandbox Code Playgroud)
(请注意,保留Stream
将导致在文档中警告的备忘录问题).使用它很简单:
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)
Run Code Online (Sandbox Code Playgroud)