A function that takes another function as an argument is called a higher order function. Like any other function parameter we give type as Int=>Int which indicates that f expects an integer as input and integer as a return type(........, f:Int=>Int). A complete example is shown which uses a Higher order function and tail recursion.
println(formatResult("Factorial of ", 7, factorial))
}
// nth fibonacci number using tail recursions
def febonacci(n:Int):Int={
@annotation.tailrec
def nextNum(num1: Int, num2:Int, n :Int):Int={
if(n==0) num2+num1
else nextNum(num2,num2+num1,n-1)
}
nextNum(0,1,n-2)
}
def factorial(n:Int):Int={
@annotation.tailrec
def fact(num:Int, acc:Int):Int={
if(num<=0) acc
else fact(num-1, num*acc)
}
fact(n,1)
}
def formatResult(name:String, n:Int, g:Int=>Int )={
val msg="The %s %d is %d"
msg.format(name,n,g(n))
}
}
object Demo{
def main(args:Array[Strings]): Unit ={
println(formatResult("Nth febonacci number where value of N is", 5, febonacci))println(formatResult("Factorial of ", 7, factorial))
}
// nth fibonacci number using tail recursions
def febonacci(n:Int):Int={
@annotation.tailrec
def nextNum(num1: Int, num2:Int, n :Int):Int={
if(n==0) num2+num1
else nextNum(num2,num2+num1,n-1)
}
nextNum(0,1,n-2)
}
def factorial(n:Int):Int={
@annotation.tailrec
def fact(num:Int, acc:Int):Int={
if(num<=0) acc
else fact(num-1, num*acc)
}
fact(n,1)
}
def formatResult(name:String, n:Int, g:Int=>Int )={
val msg="The %s %d is %d"
msg.format(name,n,g(n))
}
}
No comments:
Post a Comment