Skip to content

Instantly share code, notes, and snippets.

@timyates
Created May 5, 2016 20:42
Show Gist options
  • Select an option

  • Save timyates/2f703d1fb0e5d663556e74443ab86ce3 to your computer and use it in GitHub Desktop.

Select an option

Save timyates/2f703d1fb0e5d663556e74443ab86ce3 to your computer and use it in GitHub Desktop.

Revisions

  1. timyates created this gist May 5, 2016.
    14 changes: 14 additions & 0 deletions uncurry.groovy
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,14 @@
    // 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]]