Home > OS >  Is this scala function using right-fold or left-fold?
Is this scala function using right-fold or left-fold?

Time:11-10

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)

CodePudding user response:

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) ... )))
  • Related