Cω - Samples

Streams Tutorial

This tutorial shows how to create and use the stream type in a simple program. The program can be compiled using the Cω compiler.

Sample Files

To run this tutorial, you may use the following project and source files:

These files are located in the \samples\Basics\Streams subdirectory under the path where you installed Cω, which by default is C:\Program Files\Comega.

Tutorial

This tutorial is divided into the following sections:

Streams in General

Central to Cω is the notion of a stream. Like arrays, streams are homogenous collections of a particular type. However unlike arrays they are lazy, i.e. constructed only when needed.

Streams are sometimes also called iterators and from a functional point of view they are the same.

Declaring Streams

When declaring a stream of zero or more elements of a certain type, you need to append an asterisk (*) to the element type of the stream, such as "int*" for a stream of integers. The following shows this for a variable named OneToTen.

int* OneToTen = FromTo(1,10);

Generating Streams

A stream generator is just like an ordinary method but instead of returning a single value, it may yield a stream of values repeatedly. For example, an application of the function FromTo(n,m) generates a stream of integers n, n+1, ...m.

   int* FromTo(int start, int end) {
    for (i = start; i <= end; i++) yield return i;
   }

Using foreach with Streams

Streams implements the IEnumerable interface and therefore one can iterate over the elements of the stream using the foreach statement. For instance, to print a stream of integers from 1 to 10 one could code the following foreach loop:

foreach{int j in OneToTen){
   Console.WriteLine(j);}

Example

The following is a complete Cω program that declares a stream and prints the elements within that stream using the concepts discussed above.

using System;
public class Streams {
    // generate s, s+1, ..., e
    static int* FromTo(int s, int e) {
        for (int i = s; i <= e; i++) yield return i;
    }
    public static void Main() {
        int* OneToTen = FromTo(1,10);
        // prints 1, ..., 10
        foreach(int j in OneToTen){
            Console.WriteLine(j);
        };
    }
}

Output

1
2
3
4
5
6
7
8
9
10