Finding X cube + y by using the conventional and Higher-Order Function

27 views
Skip to first unread message

Gokula Krishnan D

unread,
Nov 17, 2015, 8:10:46 AM11/17/15
to scala-user
Hello All -

I would like to understand the difference between the Convention way of function and Higher-Order function.

Let me go with an example, X Cube + Y   For the instance my inputs are X= 2 and Y = 5 so the expected result is 13. I'm able to implement the code in both the ways i.e 13

It would be great if you could benefit and advantage of Higher-Order function. And please correct me if my way of implementing the Solution # 2 is not correct.

// Solution # 1

object funXcubeplusY_normal extends App {

println(sum(cube(2),5))

def sum(x:Int,y:Int):Int= x+y

def cube(x:Int):Int= x*x*x

}
Output:
13

//Solution # 2
object funXcubePlusY_HigherOrder extends App {

println("Sum of 2 Cube plus 5 = " + sum(cube(funXcubePlusY_HigherOrder.fncube,2),5))

def sum(x:Int,y:Int):Int = x + y

def cube(m:Int=> Int,n:Int)= m(n)

def fncube[m](m:Int):Int= m*m*m
}

Ouput: 

Sum of 2 Cube plus 5 = 13


Oliver Ruebenacker

unread,
Nov 17, 2015, 9:42:20 AM11/17/15
to Gokula Krishnan D, scala-user

     Hello,

  Your example use a higher-kinded function, but it is not very useful.

  A classical example of a higher-kinded function is a function that finds the zeros (approximately) of another function:

scala> def cutX(x1: Double, x2: Double, f: Double => Double) = { val y1 = f(x1); val y2 = f(x2); (x1*y2 - x2*y1) / (y2 - y1) }
cutX: (x1: Double, x2: Double, f: Double => Double)Double

scala> def zero(f: Double => Double) : Double = { var x1 = 1.0; var x2 = 2.0; while(x1 != x2 && !x1.isNaN && !x1.isInfinite) { val x0 = cutX(x1, x2, f); x2 = x1; x1 = x0 }; x2 }
zero: (f: Double => Double)Double

scala> val f = (x:Double) => x + 10*Math.cos(x)
f: Double => Double = <function1>

scala> val x0 = zero(f)
x0: Double = 1.7463292822528529

scala> f(x0)
res9: Double = -8.881784197001252E-16

     Best, Oliver

--
You received this message because you are subscribed to the Google Groups "scala-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scala-user+...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



--
Oliver Ruebenacker
Senior Software Engineer, Diabetes Portal, Broad Institute

Reply all
Reply to author
Forward
0 new messages