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:
Let us take an simple example :
Below code can be used to create such a stream:
Now we can create an “infinite” stream using the following command:
The keyword
lazy designates that the value assigned to the constant N should not be evaluated. Now for the following expression:
Your output would be :
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 :
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:
Let us take an simple example :
Below code can be used to create such a stream:
- def numsFrom (n :Int):Stream[Int] = Stream.cons(n,numsFrom (n+1))
- lazy val N = numsFrom(0)
- N take 10 print
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 :
沒有留言:
張貼留言