This is a follow-up to my previous question. Suppose I would like to make a Stream of all strings matching ^a+b+$ (one or more "a" and then one or more "b").
I am coding it as follows:
def interleave(s1:Stream[String], s2:Stream[String]): Stream[String] =
if (s1.isEmpty) s2 else Stream.cons(s1.head, interleave(s2, s1.tail))
def generate(s1:Stream[String], s2:Stream[String]): Stream[String] =
if (s1.isEmpty) s1 else interleave(s2.map(s1.head + _), generate(s1.tail, s2))
def as:Stream[String] = Stream.cons("a", as.map(_ + "a"))
def bs:Stream[String] = Stream.cons("b", bs.map(_ + "b"))
def solve = generate(as, bs)
Unfortunately solve fails with out of memory. However it works fine for finite streams: for instance solve(as take 10, bs take 10)
How would you fix the code above? Would you prefer another way to solve the problem?