I thought that reduceLeft and reduceRight just differs in order of traversing the list, like iterating it from left to right and right to left respectively and doing an operation (since i was thinking from iterating array from coding perspective) but i realised its not.

Addition and multiplication didn’t give me any clue as it holds **The Associative Property**.

(numbers.reduceLeft(_ * _) == numbers.reduceRight(_ * _)) ==
(numbers.reduceLeft(_ + _) == numbers.reduceRight(_ + _))

So i was wondering where we really need the distinction, trying to think of situation where i really need reduceRight and not reduceLeft in our application, (thinking that i can reverse the array and do reduceLeft and its same)

The following condition

wrongReduceRight(numbers) == reduceLeft(reverse(numbers))

is true in java for my wrongly assumed code and in scala it doesn’t hold.

**so its clear that is different than what i initially thought.**

**reduceLeft in Java:**

/*evaluated to -13 correctly*/
int[] numbers = {1, 2, 3, 4, 5};
int total = numbers[0];
for (int index = 1; index < numbers.length; index++) {
total -= numbers[index];
}

**reduceRight in Java:**

/*wrong reduceRight*/
int total = numbers[numbers.length - 1];
for (int index = numbers.length - 2; index >= 0; index--) {
total -= numbers[index];
}

But thats not the case as the code in java evaluated to -5 but in scala it’s 3.

The reason being is that scala take the last and pair and evaluates from right to left by substituting the values.

reduceRight is evaluated like

(1 – (2 – (3 – (4 – 5))))

(1 – (2 – (3 – (4 – 5))))

(1 – (2 – (3 – (-1))))

(1 – (2 – (4)))

(1 – (-2))

(3)

The code in java i’ve created for the reduceRight

private static int reduceRight(int[] numbers) {
int result = 0;
if (numbers.length < 2) {
return numbers[0];
}
if (numbers.length >= 2)
result = numbers[numbers.length - 2] - numbers[numbers.length - 1];
for (int index = numbers.length - 3; index >= 0; index--) {
System.out.print(numbers[index] + " with " + result + "; ");
result = numbers[index] - result;
}
return result;
}

reduceRight(numbers); //now evaluated to 3 correctly.

scala code:

numbers.reduceLeft(_ - _) //evaluates to -13
numbers.reduceRight(_ - _) // evaluates to 3

for more understaing of scala’s _ in in reduceLeft: http://www.codecommit.com/blog/scala/quick-explanation-of-scalas-syntax

### Like this:

Like Loading...

*Related*