【问题标题】:Is there a way to refer to an operator as a two-argument closure?有没有办法将运算符称为双参数闭包?
【发布时间】:2016-05-04 22:16:26
【问题描述】:

有时我需要将运算符作为闭包传递,如下所示:

do.some.thing() { x,y -> x+y }

我想知道是否有任何类似于"method pointer" syntax 的速记“运算符指针”语法,它可以让我得到已经包裹在两个参数闭包中的运算符。

我看到大多数算术运算符都可以用作 Number 和相关类的方法:

public Number plus(Number right)

Add two numbers and return the result.

但它们是实例方法,我不知道是否可以使用 method pointer operator .& 将它们变成两个参数的闭包。

【问题讨论】:

    标签: groovy closures operators


    【解决方案1】:

    你也可以做这种事情......

    不确定uncurry 是否正确,但它几乎是正确的;-)

    import org.codehaus.groovy.runtime.MethodClosure
    
    def uncurry(MethodClosure c) {
        {a, ...b -> a."$c.method"(*b) }
    }
    

    然后,要从 Number.plus 进行 2 arg 闭包,您可以这样做:

    def plus = uncurry(Number.&plus)
    

    然后:

    assert plus(1, 2) == 3
    

    这也适用于其他方法句柄:

    def collate = uncurry(List.&collate)
    assert collate([1, 2, 3, 4, 5], 2, true) == [[1, 2], [3, 4], [5]]
    

    【讨论】:

    • 注:uncurry 绝对不是在这里使用的正确术语……不确定它有名字
    【解决方案2】:

    不,没有这样的运算符。

    方法指针运算符不起作用,因为它创建的MethodClosure 基本上有一个对象,在本例中是Number 类和一个方法名称。所以如果你这样做......

    def c = Number.&plus
    

    然后调用c 将尝试在Number 上调用plus(),这当然行不通。

    我能想到的唯一捷径是声明一次操作符闭包,然后根据需要简单地重用它们。

    【讨论】:

      猜你喜欢
      • 2013-06-06
      • 2019-07-03
      • 1970-01-01
      • 2013-01-07
      • 1970-01-01
      • 1970-01-01
      • 2015-06-05
      • 1970-01-01
      • 2020-02-26
      相关资源
      最近更新 更多