Home > other >  Why is foldRight not giving correct count?
Why is foldRight not giving correct count?

Time:03-01

I am trying to calculate the number of elements in a list using foldRight and foldLeft method while foldLeft gives me a correct count foldRight does not. Where am i wrong in the code ?

  def count(arr:List[Int]):Int = {
      arr.foldRight(0)((B,_) => B 1)
    //arr.foldLeft(0)((B,_) => B 1)
  }

val countElements = count(1::2::3::4::Nil)
println(countElements)

The above code returns 2 for foldRight and 4 for foldLeft.

CodePudding user response:

You've swapped the arguments around for foldRight because with fold right the tuple arguments are the other way round, so you are discarding the accumulator and instead adding 1 to the last element (which with foldRight is the first element in the input) so the end result is 2 (the first element 1, plus 1)

If you swap those arguments around i.e.arr.foldRight(0)((_,B) => B 1) you get the expected result of 4

  • Related