1

I am implementing takeWhile method of trait Stream via foldRight. My foldRight is following:

trait Stream[+A] {
  def foldRight[B](z: => B)(f: (A, => B) => B): B =
    uncons.map(t => {
      f(t._1, t._2.foldRight(z)(f))
    }).getOrElse(z)
}

My takeWhile is

def takeWhile(p: A => Boolean): Stream[A] =
  uncons.filter(t => p(t._1)).map(t => Stream.cons(t._1, t._2.takeWhile(p))).getOrElse(Stream.empty)

But I want it to be implemented via foldRight. Here is the code:

def takeWhileViaFoldRight(p: A => Boolean): Stream[A] =
  foldRight(Stream.empty)((x, acc) => {
    if (p(x)) Stream.cons(x, acc) else Stream.empty
  })

But my x in Stream.cons expression is underlined red with the following error: type mismatch; found : x.type (with underlying type A) required: Nothing. I guess this is because foldRight start value is Stream.empty -- with no type A indicated hence considered to be Nothing. If this is the case -- how can I tell foldRight that its return value is A, not Nothing? If not -- what's the problem then?

Vadim Samokhin
  • 3,378
  • 4
  • 40
  • 68

1 Answers1

1

The courtesy of jdevelop's comment:

foldRight(Stream.empty[A])

will do the thing.

Community
  • 1
  • 1
Vadim Samokhin
  • 3,378
  • 4
  • 40
  • 68