First-class functions: Difference between revisions

Content added Content deleted
Line 1,160: Line 1,160:


=={{header|Scala}}==
=={{header|Scala}}==
<lang scala>def cube = (x:Double) => x*x*x
<lang scala>
import math._
def cuberoot = (x:Double) => Math.pow(x,1.0/3)


// functions as values
def compose[A,B,C](f:B=>C,g:A=>B) = (x:A)=>f(g(x))
val cube = (x: Double) => x * x * x
val cuberoot = (x: Double) => pow(x, 1 / 3d)


// higher order function, as a method
def fun = List(Math.sin _, Math.cos _, cube)
def compose[A,B,C](f: B => C, g: A => B) = (x: A) => f(g(x))
def inv = List(Math.asin _, Math.acos _, cuberoot)


// partially applied functions in Lists
def comp = fun zip inv map Function.tupled(_ compose _)
val fun = List(sin _, cos _, cube)
val inv = List(asin _, acos _, cuberoot)


// composing functions from the above Lists
comp.foreach(f=>println(f(0.5)))</lang>
val comp = (fun, inv).zipped map (_ compose _)


// output results of applying the functions
comp foreach {f => println(f(0.5))}
</lang>
Here's how you could add a composition operator to make that syntax prettier:
Here's how you could add a composition operator to make that syntax prettier:


<lang scala>class SweetFunction[B,C](f:B=>C) {
<lang scala>class SweetFunction[B,C](f: B => C) {
def o[A](g:A=>B) = (x:A)=>f(g(x))
def o[A](g: A => B) = (x: A) => f(g(x))
}
}
implicit def sugarOnTop[A,B](f:A=>B) = new SweetFunction(f)
implicit def sugarOnTop[A,B](f: A => B) = new SweetFunction(f)


//and now you can do things like this
// now functions can be composed thus
println((cube o cube o cuberoot)(0.5))</lang>
println((cube o cube o cuberoot)(0.5))</lang>