Search code examples
functional-programminggocurryingpartial-application

How can go-lang curry?


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.


Solution

  • To extend on the previous answer, which allows you to take an arbitrary number of arguments:

    package main
    
    import (
        "fmt"
    )
    
    func mkAdd(a int) func(...int) int {
        return func(b... int) int {
            for _, i := range b {
                a += i
            }
            return a
        }
    }
    
    func main() {
        add2 := mkAdd(2)
        add3 := mkAdd(3)
        fmt.Println(add2(5,3), add3(6))
    }