@rkenmi - Summation with rationals

Summation with rationals


Using Scala and the powers of Recursion.

Summation with rationals


Back to Top

Updated on June 10, 2017

Given some lower bound a = na/da and upper bound nb/db, write a function that calculates the summation of f(nk/dk), where k is the index, n represents numerator, and d represents denominator.

An example: if a =1/2 and b = 4/5, then you should calculate f(1/2)+f(2/3)+f(2/4)+ f(3/4)+ f(3/5)+f(4/5)

def sum (f: Rational => Rational)(a: Rational, b: Rational) : Rational = {  
    val k = a
    val total = new Rational(0, 1)

    def innerSum (f: Rational => Rational) ( k: Rational, total : Rational) : Rational = {
        if (a <= k && k <= b && k.rawDenom <= a.maxDenom(b)){
            println(k)
            innerSum (f) ( new Rational(k.rawNumer + 1, k.rawDenom) , total + f(k))
        }
        else if (k > b)
            innerSum (f) (new Rational(1, k.rawDenom + 1), total)
        else if (k.rawDenom > a.maxDenom(b))
            total
        else
            innerSum (f) ( new Rational(k.rawNumer + 1, k.rawDenom) ,total)
        }

    innerSum(f)(k, total)
}

Article Tags:
Scalafunctional programmingrecursion