Combining streams in Java

July 31, 2013

Given an interface Stream:

interface Stream<A> {
  A head();
  Stream<A> tail();
}

Constant streams

Write the functions zeroes, ones, and twos, which return streams of values 0, 1, and 2, respectively:

Stream<Integer> zeroes() {
  return ???; // 0 -> 0 -> 0 -> 0 -> ...
}

Stream<Integer> ones() {
  return ???; // 1 -> 1 -> 1 -> 1 -> ...
}

Stream<Integer> twos() {
  return ???; // 2 -> 2 -> 2 -> 2 -> ...
}

Natural numbers streams

Write the functions evens and odds, which return streams of the even natural numbers (0, 2, 4, ...) and the odd natural numbers (1, 3, 5, ...), respectively:

Stream<Integer> evens() {
  return ???; // 0 -> 2 -> 4 -> 6 -> ...
}

Stream<Integer> odds() {
  return ???; // 1 -> 3 -> 5 -> 7 -> ...
}

Combined streams

Write the function combine, which interleaves its argument streams in constant time:

static <A> Stream<A> combine(Stream<A>... ss) {
  return ???; // combine(evens(), odds()) = 0 -> 1 -> 2 -> 3 -> ...
}