Creating Stream

Creating Stream

Lets create a Stream of random printable characters (except '.'). The Stream length will also be random

class MyBasicStream extends scalqa.Stream.A.Basic[Char] {
  val source = scala.util.Random
  var value = '.'

  def prime: Boolean = value != '.' || {value = source.nextPrintableChar; value != '.'}

  def pump: Char = {val v = value; value = '.'; v}
}

println(new MyBasicStream) // Might print ~(L, 6, w, J, m, N, P, m, J, Q)

prime means: get next element ready. If prime returns false, the Stream ends

pump means: return next element

Important Stream rule is: pump is never called without calling prime first, making sure next element is ready

Otherwise prime/pump is similar to Iterator's hasNext/next, and can be used for standard iteration:

val s = new MyBasicStream
while(s.prime) s.pump


Creating Specialized Stream

For a specialized Stream, which will not auto-box primitives, a specialized base can be used. The first line of the above example should read

class MyBasicStream extends scalqa.Stream.A.Chars

There are bases for all primitives at Stream.A package


Creating Indexed Stream

Stream from an indexed source is processed differently with wide variety of optimizations

Lets create a Stream of characters from word "Hello"

class MyIndexedStream extends scalqa.Stream.A.Indexed[Char] {
  val source = "Hello"

  protected def _size: Int = source.length

  protected def _apply(i: Int): Char = source.charAt(i)
}

println(new MyIndexedStream) // Prints ~(H, e, l, l, o)


Creating Indexed Specialized Stream

In the above example, extend scalqa.Stream.A.Chars.Indexed


Optimizations

When creating a custom Stream, methods defined in Stream.A.Basic.Defaults can be overridden to further enhance performance