Exercise 5.2.4 Can you write an even more general function which generalizes both sum and product?
This function abstracts out the operation which can be passed in as a sum or product function. One thing to be noted here is that an extra argument needs to be passed as the base case which would be 0 for a sum and 1 for a product.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object OperatorOverRange { | |
def operateOverRange(f: Int => Int)(operate: (Int, Int) => Int)(base: Int)(a: Int, b:Int): Int = | |
if (a > b) base else operate(f(a), operateOverRange(f)(operate)(base)(a + 1, b)) | |
def main(args: Array[String]) { | |
println("Sum of range of numbers from 3 to 8 is: " + operateOverRange(x => x)((x,y) => x + y)(0)(3,8)) | |
println("Product of range of numbers from 3 to 8 is: " + operateOverRange(x => x)((x,y) => x * y)(1)(3,8)) | |
} | |
} |
No comments:
Post a Comment