Apparently, since James isn't on the list this reply bounced..
---------- Forwarded message ----------
From: James Roper <
james...@typesafe.com>
Date: Tue, Jun 25, 2013 at 11:35 AM
Subject: Re: On the need for an Empty input case in the Iteratee pattern
To: Ben Hutchison <
brhut...@gmail.com>
Cc: "
scala...@googlegroups.com" <
scala...@googlegroups.com>, Runar
Bjarnason <
runar...@gmail.com>, Josh Suereth
<
joshua....@gmail.com>
Hi Ben,
There is one main purpose for Empty, and that is for use with Done and
flatMap. Done must contain the left over input, so for example, if
you had a dropWhile iteratee:
def dropWhile[E](p: E => Boolean): Iteratee[E, Unit] = Cont {
case Input.El(e) if p(e) => dropWhile(p)
case Input.Empty => dropWhile(p)
case in => Done(Unit, in)
}
Now imagine this code:
Enumerator(1, 2, 3, 4) &> dropWhile[Int](_ < 3).flatMap(_ => Iteratee.getChunks)
The result should be Seq(3, 4), but the dropWhile iteratee consumes 3
from the enumerator, how does Iteratee.getChunks get that 3? The way
it works is it passes 3 to Done as the left over input, and that
allows the implementation of flatMap to feed the left over 3 into the
getChunks iteratee before consuming more input from the enumerator.
But what if the iteratee doesn't have any left over input when it's
done? For example:
def drop[E](n: Int): Iteratee[E, Unit] = if (n <= 0) {
Done(Unit, Input.Empty)
} else Cont {
case _: Input.El => drop(n - 1)
case Input.Empty => drop(n)
case eof: Input.EOF => Done(Unit, eof)
}
As you can see, it needs to instead pass empty (this is actually the
default value for the argument), and then the implementation flatMap
can know that there's nothing to feed to the next iteratee.
Another convenient use for empty is for dropping input with an enumerator:
Enumerator.mapInput[Int] {
case Input.El(v) if v < 3 => Input.Empty
case other => other
}
I guess another way it could be implemented is to have Option[Input]
as the left over input for Done. This would make implementing
iteratees simpler since they wouldn't need to handle empty. I'm not
sure of any other purposes for empty.
Cheers,
James
--
James Roper
Software Engineer
Typesafe – Empowering professional developers to build amazing apps.
Twitter: @jroper
See you at Scala Days 2013 in NYC!
June 10th - June 12th
www.scaladays.org