I am learning scala from coursera. In the reduceLeft and reduceRight description this comes along:
and then on the very next slide the teacher says this code pattern is abstracted out as reduceLeft
My questions:
- I think the pattern in the first slide is
reduceRightand notreduceLeft. Can you please help me understand where I am mistaken? For example: an addition operator on[1,2,3]would lead to(1+sum(2,3))from the first slide which, I think, is reduceRight. reduceLeft should be(sum(1,2)+3) - I am not able to implement the
reduceLeftasreduceRightis implemented raw in the first slide using thecasestatements? Can you please guide me in the right direction on how to do it?


Re 1.:
Indeed, as already confirmed in the comments, the pattern in the first slide is
reduceRight.I think the point of the second slide is to say "that pattern of reducing a list can be abstracted out using a generic method from the standard library" (not "the pattern of the specific solution from the previous slides corresponds to
reduceLeft").Both
reduceLeftandreduceRightwould be suitable to implementsum. However: when bothreduceLeft/reduceRight(orfoldLeft/foldRight) are suitable for a solution, in scala one usually prefers theLeftvariant (especially when working withLists) because its implementation is slightly more efficient onLists. That's most certainly the motivation for focusing onreduceLefton the second slide.Re 2.:
If you want to implement the
sumfrom the first slide in a left-reducing way, you will need three cases:I leave it to you to fill out the
???s.Note that it will not be possible to implement this left-reducing
sumin a tail-recursive manner (unless you introduce an additional helper function with a different signature).