Created
May 5, 2016 20:42
-
-
Save timyates/2f703d1fb0e5d663556e74443ab86ce3 to your computer and use it in GitHub Desktop.
Uncurry(?) in Groovy
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
// Change a method reference into a closure that takes the delegate as the first parameter | |
import org.codehaus.groovy.runtime.MethodClosure | |
def uncurry(MethodClosure c) { | |
{a, ...b -> a."$c.method"(*b) } | |
} | |
// So uncurrying Number.plus gives us a closure that will take {x, y -> x.plus(y)} | |
def plus = uncurry(Number.&plus) | |
assert plus(1, 2) == 3 | |
// Also works with other methods with multiple parameters | |
def collate = uncurry(List.&collate) | |
assert collate([1, 2, 3, 4, 5], 2) == [[1, 2], [3, 4]] |
The last one should be like so:
assert collate([1, 2, 3, 4, 5], 2) == [[1, 2], [3, 4],[5]]
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Definitely not uncurrying