In: Computer Science
Question: Write a method named reduce that:
● Takes a function of type (A, A) => A
● Returns A
● Combines all the elements of the list into a single value by
applying the provided function
to all elements
○ You may assume the function is commutative
● If the list has size 1, return that element without calling the
provided function
Example: If head stores a reference to the List(4, 6, 2)
head.reduce((a: Int, b: Int) => a + b) == 12
Programming language is Scala
Modified Code with explanation in comments:
object ListSum {
def main(args: Array[String]) {
var i=0
var sum=0
//head will store the value of list
val head=List(2)
//if size of list=1, then it will directly print the list
//else it will call the function named
reduce(Int,Int)==>Int
//return Int
if(head.size==1){
print(head(0))
}
else{
for( i <- 0 to (head.size-2) by 2)
{
sum+=reduce(head(i),head(i+1))
}
if(head.size%2!=0){
sum+=reduce(head(head.size-1),0)
}
print(sum)
}
}
//reduce funtion of type (A,A) => A(return type)
def reduce(a:Int,b:Int) : Int =
{
return a+b
}
}
--------------------------------------------------------------------------------------------------------------------------
Screenshot of Output with Code: