79811170

Date: 2025-11-06 10:51:27
Score: 0.5
Natty:
Report link

I agree with all the senior resources who answered, but these are my findings -

val numbers = List(1, 2, 3, 4, 5)
val sum = numbers.foldLeft(0)(_ + _)
# Output sum: Int = 15
val sum = numbers.foldRight(0)(_+_)
# Output: Int = 15
#---------------for addition its working fine --------------


# but when you perform subtract operation then it behaves differently 
val sum = numbers.foldRight(0)(_-_)
# Output sum: Int = 3
val sum = numbers.foldLeft(0)(_-_)
# Output  sum: Int = -15

In conclusion, when performing a fold left or fold right operation, the output may differ based on the anonymous function. Execution order is different for both

Taking same example List(a,b,c,d)

In foldLeft it goes a -> b

And for foldRight it goes b->a

You can read the documentation for further information.

Thanks

Reasons:
  • Blacklisted phrase (0.5): Thanks
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Low reputation (1):
Posted by: ShubhGurukul