How can go-lang curry?

lazywei picture lazywei · Oct 16, 2013 · Viewed 13.6k times · Source

In functional programming likes Haskell, I can define function

add a b = a+b

Then add 3 will return a function that take one parameter and will return 3 + something

How can I do this in GO?

When I define a function that take more than one (say n) parameters, can I only give it one parameter and get another function that take n-1 parameters?

Update:

Sorry for the imprecise words in my original question.

I think my question should be asked as two qeustions:

  • Is there partial application in GO?
  • How GO do function curry?

Thanks TheOnly92 and Alex for solving my second question. However, I am also curious about the first question.

Answer

alex picture alex · Oct 16, 2013

Perhaps something like

package main

import (
    "fmt"
)

func mkAdd(a int) func(int) int {
    return func(b int) int {
        return a + b
    }
}

func main() {
    add2 := mkAdd(2)
    add3 := mkAdd(3)
    fmt.Println(add2(5), add3(6))
}