简体   繁体   中英

scala Stream.takeWhile

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 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?

The courtesy of jdevelop 's comment :

foldRight(Stream.empty[A])

will do the thing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM