Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala 递归地建立一个向量_Scala_Functional Programming_Scala Collections - Fatal编程技术网

Scala 递归地建立一个向量

Scala 递归地建立一个向量,scala,functional-programming,scala-collections,Scala,Functional Programming,Scala Collections,我有一个函数f(a:a):a和一个整数N。我想编写一个函数,返回以下向量[a]: 向量(a,f(a),f(f(a)),f(f(a)),…,f^{N}(a)) 其中f^{N}表示递归地应用f次N可能相对较大。我正在寻找一种解决方案,它不需要反转数据结构或多次遍历它。显然,有很多方法可以做到这一点;我正在寻找功能性、惯用和可读的代码。(1到N)。foldLeft(Vector(a)){(acc,a)=>acc:+f(acc.last)}(1到N)。foldLeft(Vector(a)){(acc,a

我有一个函数
f(a:a):a
和一个整数
N
。我想编写一个函数,返回以下向量[a]:

向量(a,f(a),f(f(a)),f(f(a)),…,f^{N}(a))


其中
f^{N}
表示递归地应用
f
次<代码>N可能相对较大。我正在寻找一种解决方案,它不需要反转数据结构或多次遍历它。显然,有很多方法可以做到这一点;我正在寻找功能性、惯用和可读的代码。

(1到N)。foldLeft(Vector(a)){(acc,a)=>acc:+f(acc.last)}
(1到N)。foldLeft(Vector(a)){(acc,a)=>acc:+f(acc.last)}
{Vector,List,Array,…}。迭代器

定义迭代[A](开始:A,长度:Int)(f:(A)⇒ A) :矢量[A]

产生 集合,其中包含函数的重复应用程序 价值启动集合len的开始值,该值为 函数集合中包含的元素重复 applied返回序列开始时带有len值的集合, f(开始),f(开始)),…

或者,如果您真的想自己实现它,这里有一个可能的解决方案

scala> def iterator[A](start: A, len: Int)(f: A => A): Vector[A] = len match {
     |   case 0 => Vector()
     |   case _ => start +: iterator(f(start), len-1)(f)
     | }
iterator: [A](start: A, len: Int)(f: A => A)Vector[A]

scala> iterator(10000, 100)(f)
res1: Vector[Int] = Vector(10000, 5000, 2500, 1250, 625, 1876, 938, 469, 1408, 
704, 352, 176, 88, 44, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 
1, 4, 2, 1, 4, 2, 1, 4, 2, 1, 4, 2, 1, 4, 2, 1, 4, 2, 1, 4, 2, 1, 4, 2, 1, 4, 2, 
1, 4, 2, 1, 4, 2, 1, 4, 2, 1, 4, 2, 1, 4, 2, 1, 4, 2, 1, 4, 2, 1, 4, 2, 1, 4, 2, 
1, 4, 2, 1, 4, 2, 1, 4, 2, 1, 4, 2, 1, 4, 2, 1, 4)

{向量,列表,数组,…}。迭代器

定义迭代[A](开始:A,长度:Int)(f:(A)⇒ A) :矢量[A]

产生 集合,其中包含函数的重复应用程序 价值启动集合len的开始值,该值为 函数集合中包含的元素重复 applied返回序列开始时带有len值的集合, f(开始),f(开始)),…

或者,如果您真的想自己实现它,这里有一个可能的解决方案

scala> def iterator[A](start: A, len: Int)(f: A => A): Vector[A] = len match {
     |   case 0 => Vector()
     |   case _ => start +: iterator(f(start), len-1)(f)
     | }
iterator: [A](start: A, len: Int)(f: A => A)Vector[A]

scala> iterator(10000, 100)(f)
res1: Vector[Int] = Vector(10000, 5000, 2500, 1250, 625, 1876, 938, 469, 1408, 
704, 352, 176, 88, 44, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 
1, 4, 2, 1, 4, 2, 1, 4, 2, 1, 4, 2, 1, 4, 2, 1, 4, 2, 1, 4, 2, 1, 4, 2, 1, 4, 2, 
1, 4, 2, 1, 4, 2, 1, 4, 2, 1, 4, 2, 1, 4, 2, 1, 4, 2, 1, 4, 2, 1, 4, 2, 1, 4, 2, 
1, 4, 2, 1, 4, 2, 1, 4, 2, 1, 4, 2, 1, 4, 2, 1, 4)

太棒了,谢谢你给我介绍Vector.iterate!太棒了,谢谢你给我介绍Vector.iterate!