在Scala中使用Streams进行排序

Mic*_*ael 5 scala stream

假设有一个序列a[i] = f(a[i-1], a[i-2], ... a[i-k]).你会如何streams在Scala中使用它进行编码?

and*_*lla 3

a使用数组 for和另一个k参数,并让 fi 带有参数的函数,可以将其推广到任何 k rest...

def next(a1:Any, ..., ak:Any, f: (Any, ..., Any) => Any):Stream[Any] {
  val n = f(a1, ..., ak)
  Stream.cons(n, next(a2, ..., n, f))
}

val myStream = next(init1, ..., initk)
Run Code Online (Sandbox Code Playgroud)

为了第1000次做next.drop(1000)

更新以展示如何使用可变参数来完成此操作。请注意,传递的函数没有元数检查:

object Test extends App {

def next(a:Seq[Long], f: (Long*) => Long): Stream[Long] = {
  val v = f(a: _*)
  Stream.cons(v, next(a.tail ++ Array(v), f))
}

def init(firsts:Seq[Long], rest:Seq[Long], f: (Long*) => Long):Stream[Long] = {
  rest match {
    case Nil => next(firsts, f)
    case x :: xs => Stream.cons(x,init(firsts, xs, f))
  }
}

def sum(a:Long*):Long = {
  a.sum
}

val myStream = init(Seq[Long](1,1,1), Seq[Long](1,1,1), sum)


myStream.take(12).foreach(println)
Run Code Online (Sandbox Code Playgroud)

}