Skip to content

Commit

Permalink
Updated answer file for stream take/drop
Browse files Browse the repository at this point in the history
  • Loading branch information
pchiusano committed Dec 15, 2014
1 parent 1f6b487 commit f24c4c0
Showing 1 changed file with 13 additions and 18 deletions.
31 changes: 13 additions & 18 deletions answerkey/laziness/02.answer.scala
Original file line number Diff line number Diff line change
Expand Up @@ -2,25 +2,20 @@
/*
`take` first checks if n==0. In that case we need not look at the stream at all.
*/
def take(n: Int): Stream[A] =
if (n > 0) this match {
case Cons(h, t) if n == 1 => cons(h(), Stream.empty) // we can say Stream.empty
case Cons(h, t) => cons(h(), t().take(n-1))
case _ => Stream.empty
}
else Stream() // or Stream()
def take(n: Int): Stream[A] = this match {
case Cons(h, t) if n > 1 => cons(h(), t().take(n - 1))
case Cons(h, _) if n == 1 => cons(h(), empty)
case _ => empty
}

/*

/*
Unlike `take`, `drop` is not incremental. That is, it doesn't generate the
answer lazily. It must traverse the first `n` elements of the stream eagerly.
*/
def drop(n: Int): Stream[A] = {
@annotation.tailrec
def go(s: Stream[A], n: Int): Stream[A] =
if (n <= 0) s
else s match {
case Cons(h,t) => go(t(), n-1)
case _ => Stream()
}
go(this, n)
}
@annotation.tailrec
final def drop(n: Int): Stream[A] = this match {
case Cons(h, t) if n > 0 => t().drop(n - 1)
case _ => this
}

0 comments on commit f24c4c0

Please sign in to comment.