-2

Limit number of iteration in foldLeft. I would like to terminate iteration of foldLeft based on certain condition. Condition is evaluated from different variable not from list element.

I tried using takeWhile for limiting the iteration; however takeWhile's predicate works on list's element not on external values.

val numberList = List (1.0, 2.0, 3.0, 4.5, 5.5)
var sampleList = List [Double]()
var sum = 0.0
val sumLimit = 6.0 
var param = (sampleList, sum, sumLimit)
var filteredList = numberList.foldLeft(param) {
    (p, element) => {
        if (p._2 < p._3) {
            sampleList = p._1 :+ element
            (sampleList, p._2 + element, p._3)
        } else {
            (p._1, p._2, p._3)
        }
    }
}

Above code iterates 5 times; however I want it to iterate while (p._2 < p._3). Above code should return following list of doubles (1.0, 2.0, 3.0) which it is doing; however I want to limit the number of iteration.

1 Answers1

1

Since predefined fold is stateless, short circuiting wont really work. Plain recursion (of which folds are shorthands) or iteration seems therefore closer to what you want:

def f(p, lst, acc) = ??? //your function
var filteredList = f(p,numberList,Nil)
klswt
  • 39
  • 3