First-class functions: Difference between revisions

Line 1,160:
 
=={{header|Scala}}==
<lang scala>def cube = (x:Double) => x*x*x
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
defval cuberoot = (x: Double) => Math.pow(x, 1.0 /3 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 _)
defval fun = List(Math.sin _, Math.cos _, cube)
defval inv = List(Math.asin _, Math.acos _, cuberoot)
 
// composing functions from the above Lists
comp.foreach(f=>println(f(0.5)))</lang>
defval comp = (fun zip, inv).zipped map Function.tupled(_ compose _)
 
// output results of applying the functions
comp. foreach( {f => println(f(0.5)))</lang>}
</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)
 
//and now youfunctions can dobe thingscomposed like thisthus
println((cube o cube o cuberoot)(0.5))</lang>
 
Anonymous user