Anonymous user
First-class functions: Difference between revisions
→{{header|Scala}}
Line 1,160:
=={{header|Scala}}==
<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
// 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 _)▼
// composing functions from the above Lists
comp.foreach(f=>println(f(0.5)))</lang>▼
// output results of applying the functions
</lang>
Here's how you could add a composition operator to make that syntax prettier:
<lang scala>class SweetFunction[B,C](f: B => C) {
def o[A](g: A => B) = (x: A) => f(g(x))
}
implicit def sugarOnTop[A,B](f: A => B) = new SweetFunction(f)
//
println((cube o cube o cuberoot)(0.5))</lang>
|