2016年7月26日 星期二

[Scala 文章收集] Quick Tip : Streams in Scala

Source From Here
Preface
There are cases where one has to use the first n numbers of an infinite sequence of numbers (like the Fibonacci numbers for example) but, unfortunately, there is no way to determine how many members of the sequence will be actually needed. Scala offers an better solution for the same – the ability to define infinite sized data structures whose elements are computed on demand.These data structures are called streams. A stream is a list whose elements are not computed eagerly, but rather lazily. Eager evaluation means that a function first evaluates its arguments and then it uses them, while lazy evaluation means that an argument is evaluated only when it is needed.

Scala Stream
Streams are created using the constant empty and the constructor cons, which are both defined in module scala.collection.immutable.Stream. For example, the following expression constructs a stream with elements 1 and 2:
Stream.cons(1, Stream.cons(2, Stream.empty))

Let us take an simple example :
scala> def numsFrom(n:Int):Stream[Int] = Stream.cons(n, numsFrom(n+1))
numsFrom: (n: Int)Stream[Int]

scala> lazy val N = numsFrom(0)
N: Stream[Int] =

scala> N take 10 print
warning: there was one feature warning; re-run with -feature for details
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, empty

Below code can be used to create such a stream:
  1. def numsFrom (n :Int):Stream[Int]  = Stream.cons(n,numsFrom (n+1))  
Now we can create an “infinite” stream using the following command:
  1. lazy val N = numsFrom(0)  
The keyword lazy designates that the value assigned to the constant N should not be evaluated. Now for the following expression:
  1. N take 10 print  
Your output would be :
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, empty

Let us take another simple example. Suppose we want to print the number “10” for desired times then using stream this can be written as :
scala> lazy val printTen: Stream[Int] = Stream.cons(10, printTen)
printTen: Stream[Int] =

scala> printTen take 12 print
warning: there was one feature warning; re-run with -feature for details
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, empty


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...