Skip to content

Instantly share code, notes, and snippets.

@sofoklis
Last active December 11, 2015 17:58
Show Gist options
  • Save sofoklis/4638497 to your computer and use it in GitHub Desktop.
Save sofoklis/4638497 to your computer and use it in GitHub Desktop.
Function1 examples
// Simple way to create a Function1
val succ = (x: Int) => x + 1 //> succ : Int => Int = <function1>
// Same in full version
val anonfun1 = new Function1[Int, Int] {
// Only need to specify the apply method
def apply(x: Int): Int = x + 1
} //> anonfun1 : Int => Int = <function1>
// Create one more function to compose
val toStr = (x: Int) => "Num " + x //> toStr : Int => String = <function1>
// So we can assign and pass funtions as arguments
val a = succ //> a : Int => Int = <function1>
List(1,2,3,4) map a //> res0: List[Int] = List(2, 3, 4, 5)
// Compose succ and toStr in this order
val t = succ andThen toStr //> t : Int => String = <function1>
// Check it
t(1) //> res1: String = Num 2
// Compose reverses the order of the operants, same as mathematical composition f(g(x))
val t2 = toStr compose succ //> t2 : Int => String = <function1>
// Should be the same as before
t2(1) //> res2: String = Num 2
// We can also use our "composite" function same as a regular function
List(1,2,3,4,5) map t2 //> res3: List[String] = List(Num 2, Num 3, Num 4, Num 5, Num 6)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment