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


沒有留言:

張貼留言

[JS 文章收集] 用 Node.js 學 JavaScript 語言(1)簡介與安裝

Source From  Here   簡介   Node.js  是 Ryan Dahl 基於 Google 的 V8 引擎於 2009 年釋出的一個 JavaScript 開發平台,主要聚焦於 Web 程式的開發,通常用被來寫網站。但是,要開發網站就勢必要把「 HTML,...