Suppose there is a sequence a[i] = f(a[i-1], a[i-2], ... a[i-k])
. How would you code it using streams
in Scala?
The Stream is a lazy lists where elements are evaluated only when they are needed. This is a scala feature. Scala supports lazy computation.
Sequence is an iterable collection of class Iterable. It is used to represent indexed sequences that are having a defined order of element i.e. guaranteed immutable. The elements of sequences can be accessed using their indexes. Method apply is used for the purpose of indexing.
Scala Seq is a trait to represent immutable sequences. This structure provides index based access and various utility methods to find elements, their occurences and subsequences. A Seq maintains the insertion order.
It will be possible to generalize it for any k, using an array for a
and another k
parameter, and having, f.i., the function with a rest...
parameter.
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)
in order to have the 1000th do next.drop(1000)
An Update to show how this could be done with varargs. Beware that there is no arity check for the passed function:
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With