Reputation: 39
I am trying to calculate factorial of elements present in a Scala list for suppose List(1,2,3) using Higher order function as in below code
object HigherOrderFunctionEg{
def main(args :Array[String]){
val input = args(0).toInt
val intiList :List[Int] = List.range(1,input+1)
def factorial(n: Int): Int = {
if (n == 0)
return 1
else
return n * factorial(n-1)
}
def myHigherOrderFn (factorial : Int => Unit, intiList : List[Int]) : Unit =
{
intiList.foreach(factorial)
println(intiList.foreach(factorial))
}
myHigherOrderFn(factorial, intiList)
}
}
When I am trying to scala HigherOrderFunctionEg.scala 3 I am getting output as only empty braces () where as I am expecting output like 1 2 6
Upvotes: 2
Views: 1919
Reputation: 27356
There are multiple problems:
factorial
is Int => Int
but you have used Int => Unit
foreach
returns Unit
so printing the result will always give ()
myHigherOrderFun
returns Unit
so it isn't really a function.This is a better way to write it:
def myHigherOrderFn(factorial: Int => Int, intiList: List[Int]): List[Int] =
intiList.map(factorial)
myHigherOrderFn(factorial, intiList).foreach(println)
Upvotes: 3
Reputation: 3250
The problem is the return type of factorial is Int => Unit
. It should be Int => Int
As it takes an integer and returns an integer.
You need to change your definition like this.
def myHigherOrderFn (factorial : Int => Int, intiList : List[Int]) : Unit =
intiList.foreach(e => println(factorial(e)))
Upvotes: 1