Created
April 28, 2011 04:33
-
-
Save yuroyoro/945808 to your computer and use it in GitHub Desktop.
Scalaでも>>とか<<で関数合成できるように。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
scala> trait ComposableFunction1[-T1, +R] { | |
| val f: T1 => R | |
| def >>[A](g:R => A):T1 => A = f andThen g | |
| def <<[A](g:A => T1):A => R = f compose g | |
| } | |
defined trait ComposableFunction1 | |
scala> implicit def toComposableFunction1[T1,R](func:T1 => R) = new ComposableFunction1[T1,R]{ val f = func } | |
toComposableFunction1: [T1,R](func: (T1) => R)java.lang.Object with ComposableFunction1[T1,R] | |
scala> | |
scala> val plus2 = (it:Int) => { it + 2 } | |
plus2: (Int) => Int = <function1> | |
scala> val times3 = (it:Int) => { it * 3 } | |
times3: (Int) => Int = <function1> | |
scala> val times3plus2 = plus2 << times3 | |
times3plus2: (Int) => Int = <function1> | |
scala> times3plus2(3) | |
res0: Int = 11 | |
scala> val plus2times3 = times3 << plus2 | |
plus2times3: (Int) => Int = <function1> | |
scala> plus2times3(3) | |
res1: Int = 15 | |
scala> (times3 >> plus2)(3) | |
res2: Int = 11 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment