1
def calculate(f: Int => Int, sumProd:(Int, Int)=>Int, n: Int, a:Int, b:Int):Int =
  if (a>b) n 
   else sumProd(f(a), calculate(f, sumProd, n, a+1, b))

This scala function can in a chosen number area (a to b) do chosen calculations with them: example calling:

calculate(x=>2*x, (x,y)=>x+y, 0, 2 , 4)

this calculates: 2*2 + 2*3 + 2*4 = 18

Which folding(right- or left folding) is this function using? And how to see that?

further example callings for the function:

calculate(x=>2+x, (x,y)=>x*y,1, 2 , 4)
calculate(x=>2+x, (a,b)=>a+b,0, 1, 5)
calculate(x=>2*x, (a,b)=>a+b,0, 1, 5)
Will Ness
  • 70,110
  • 9
  • 98
  • 181
  • https://stackoverflow.com/questions/73915799/what-does-eb-fb-a-b-b (answer: https://stackoverflow.com/a/73916338/5249621 ) – Dmytro Mitin Nov 09 '22 at 13:28

1 Answers1

1

What you have is equivalent to, in pseudocode,

calculate(f, sumProd, n, a, b) 
=
  fold-right( sumProd, n, map(f, [a .. b]))

where [a .. b] denotes a list of numbers from a to b, inclusive, increasing by the step of 1. In other words, it is the same as

=
  sumProd( f(a), 
    sumProd( f(a2), 
      sumProd( f(a3), 
        ... 
          sumProd( f(b), n) ... )))
Will Ness
  • 70,110
  • 9
  • 98
  • 181
  • Thought this is left-fold: (((a1 + a2) + a3) + a4) + b and what my code does is right-fold and this: a + (a2 + (a3 + (a4 + b))) but according to your pseudocode my code is right-fold and doing this: (((b+a4)+a3)+a2)+a or is it just the same? – scalaquestions Nov 09 '22 at 14:54
  • no, according to my pseudocode it does `a + (a2 + (a3 + (a4 + (b + n)))) = plus(a, plus(a2, plus(a3, plus(a4, plus(b, n)))))`. – Will Ness Nov 09 '22 at 18:59