Scala中惯用的类似Haskell的迭代?
在Haskell中,我可以通过调用以下命令获得无限多个顺序函数应用程序:Scala中惯用的类似Haskell的迭代?,scala,haskell,function-composition,Scala,Haskell,Function Composition,在Haskell中,我可以通过调用以下命令获得无限多个顺序函数应用程序: iterate :: (A -> A) -> A -> [A] 假设在scala中我有f(x:A):A。是否有一个函数会产生一系列顺序函数应用程序?像iter(f:A=>A,x:A):流[A]?有and(): 或者您可以自己编写一个,使用流: def iter[A](f: A => A, x: A): Stream[A] = { val result = f(x) result #:: i
iterate :: (A -> A) -> A -> [A]
假设在scala中我有f(x:A):A
。是否有一个函数会产生一系列顺序函数应用程序?像iter(f:A=>A,x:A):流[A]?有and():
或者您可以自己编写一个,使用流:
def iter[A](f: A => A, x: A): Stream[A] = {
val result = f(x)
result #:: iter(f, result)
}
(请注意,按住流
会导致记忆问题)。使用它非常简单:
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)
是的,它已经在图书馆里了:
基本上与@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)
并交换f
和x
的位置,可以帮助编译器:
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)
你的意思是像iter(x=>2*x,1)==Stream(1,2,4,8,?)
?Stream。也迭代。@downvoter-要不要评论一下,这样我就可以改进答案了?:-)
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)
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)