【问题标题】:Need help understanding currying using groovy closures?需要帮助理解使用 groovy 闭包的柯里化?
【发布时间】:2012-05-17 17:08:01
【问题描述】:

我试图了解柯里化在函数式编程中的工作原理。我已经通过wiki 和几个关于 SO 的相同问题。

Need help understanding lambda (currying)

What is 'Currying'?

我知道柯里化就是将一个接受 n 个参数的函数拆分为 n 个或更少的函数,每个函数只有一个参数。我从理论上理解它,但我无法在编码时连接这些点。也许是我缺乏函数式编程语言或 C# 方面的知识(正如上述问题中的许多答案所涉及的那样)。

无论如何,我了解 groovy 和 java。所以我试图在 groovy 中获得标准add(a,b) 函数的大纲,但我无法完成它。

def closure = { arg ->
   // ??
}

def add(anotherClosure , a){
    return closure // ??
}

有人可以帮助我理解使用 groovy 闭包的柯里化吗?

【问题讨论】:

  • 我在一次会议上谈论了使用 Groovy 进行函数式编程。你可以看到slides about currying with Groovy
  • 浏览了所有幻灯片。一个非常好的信息。 :)

标签: groovy functional-programming currying


【解决方案1】:

您可以通过编写一个闭包来滚动您自己的柯里化功能,该闭包接受另一个闭包和一个柯里化参数来设置,并返回一个使用该值的闭包。

// Our closure that takes 2 parameters and returns a String
def greet = { greeting, person -> "$greeting $person" }

// This takes a closure and a default parameter
// And returns another closure that only requires the
// missing parameter
def currier = { fn, param ->
  { person -> fn( param, person ) }
}

// We can then call our currying closure
def hi = currier( greet, 'Hi' )

// And test it out
hi( 'Vamsi' )

但您最好坚持使用内置的 Groovy curry 方法 as shown by jalopaba。 (还有rcurryncurry分别从右边和给定位置咖喱)

应该说,Groovy curry 方法用词不当,因为它更像是partial application 的情况,因为您不需要深入到只需要一个参数的闭包,即:

def addAndTimes = { a, b, c -> ( a + b ) * c }

println addAndTimes( 1, 2, 3 ) // 9

def partial = addAndTimes.curry( 1 )

println partial( 2, 3 ) // 9

【讨论】:

    【解决方案2】:

    您可以使用curry() 方法为闭包实例的一个或多个参数设置一个固定值:

    def add = { a, b -> a + b }
    def addFive = add.curry(5)
    addFive(3) // 5 + 3 = 8
    

    另一个例子:

    def greeter = { greeting, name -> println "${greeting}, ${name}!" }
    def sayHello = greeter.curry("Hello")
    sayHello("Vamsi") // Hello, Vamsi!
    def sayHi = greeter.curry("Hi")
    sayHi("Vamsi") // Hi, Vamsi!
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-08
      • 1970-01-01
      • 2019-01-28
      • 2018-01-24
      • 1970-01-01
      相关资源
      最近更新 更多