Scala takeWhile Method with foldLeft and foldRight

Viewed 883

I need to make takeWhile() using foldLeft() and foldRight(). I've come up with this:

def takeWhile(ls:List[Int], p:Int => Boolean): List[Int] = {
    ls.foldLeft(List[Int]())(a,z) =>
    if (p(z)) z :: a
    else a)
}

def takeWhile(ls:List[Int], p:Int => Boolean): List[Int] = {
    ls.foldRight(List[Int]())(a,z) =>
    if (p(a)) a :: z
    else z)
}

But with foldLeft when I call

takeWhile(List(1,2,3,4,5), _< 3)
takeWhile(List(1,2,3,4,5), _> 4)
takeWhile(List(5,6,7,1,2,5), _> 4)

It returns

List(2,1)
List(5)
List(5,7,6,5)

With foldRight I get

List(5)
List(5,6,7,5)

But it should be

List(1,2)
List()
List(5,6,7)

How do I make it stop when condition is not met?

3 Answers
Related