Back to Fpinscala

03.Answer

answerkey/streamingio/03.answer.md

latest602 B
Original Source
scala
def drop(n: Int): Pull[O, R] =
  if n <= 0 then this
  else uncons.flatMap:
    case Left(r) => Result(r)
    case Right((_, tl)) => tl.drop(n - 1)

def takeWhile(f: O => Boolean): Pull[O, Pull[O, R]] =
  uncons.flatMap:
    case Left(r) => Result(Result(r))
    case Right((hd, tl)) =>
      if f(hd) then Output(hd) >> tl.takeWhile(f)
      else Result(Output(hd) >> tl)

def dropWhile(f: O => Boolean): Pull[Nothing, Pull[O, R]] =
  uncons.flatMap:
    case Left(r) => Result(Result(r))
    case Right((hd, tl)) =>
      if f(hd) then tl.dropWhile(f)
      else Result(Output(hd) >> tl)