需要帮助了解使用groovy闭包的currying?

Vam*_*ani 13 groovy functional-programming currying

我试图理解currying在函数式编程中是如何工作的.我已经通过wiki和关于SO的几个问题.

需要帮助了解lambda(currying)

什么是'Currying'?

我理解currying是关于将一​​个带有n个参数的函数分成n个或更少的函数,每个函数都有一个参数.我理论上理解它,但在编码时我无法连接点.也许是因为我缺乏函数式编程语言或C#的知识(正如上面问题中的许多答案所述).

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

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

def add(anotherClosure , a){
    return closure // ??
}
Run Code Online (Sandbox Code Playgroud)

有人可以帮我理解使用groovy闭包的curry吗?

tim*_*tes 17

您可以通过编写一个带有另一个闭包和curried参数来设置的闭包来滚动自己的currying功能,并返回一个使用该值的闭包.

// 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' )
Run Code Online (Sandbox Code Playgroud)

但是你最好坚持使用内置的Groovy curry方法,如jalopaba所示.(还有从右边和在给定位置咖喱的rcurryncurry)

应该说,Groovy咖喱方法是用词不当,因为它更像是部分应用的情况,因为你不需要只需要一个参数,即:

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

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

def partial = addAndTimes.curry( 1 )

println partial( 2, 3 ) // 9
Run Code Online (Sandbox Code Playgroud)

  • +1比我的更全面的解释:-) (2认同)

jal*_*aba 10

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

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

另一个例子:

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!
Run Code Online (Sandbox Code Playgroud)