First-class functions: Difference between revisions
Content added Content deleted
Line 1,160: | Line 1,160: | ||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
<lang scala> |
<lang scala> |
||
import math._ |
|||
⚫ | |||
// functions as values |
|||
⚫ | |||
val cube = (x: Double) => x * x * x |
|||
⚫ | |||
// higher order function, as a method |
|||
⚫ | |||
⚫ | |||
⚫ | |||
// partially applied functions in Lists |
|||
⚫ | |||
⚫ | |||
⚫ | |||
// composing functions from the above Lists |
|||
⚫ | |||
⚫ | |||
// output results of applying the functions |
|||
⚫ | |||
</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) |
||
// |
// now functions can be composed thus |
||
println((cube o cube o cuberoot)(0.5))</lang> |
println((cube o cube o cuberoot)(0.5))</lang> |
||