Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 967
lazywei Avatar asked Oct 16 '13 03:10

lazywei


3 Answers

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))
}
like image 52
TheOnly92 Avatar answered Nov 03 '22 16:11

TheOnly92


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))
}
like image 32
alex Avatar answered Nov 03 '22 18:11

alex


You can take it a step further by defining a function type and then adding a method to it.

package main

import "fmt"

type Add func(int, int) int

func (f Add) Apply(i int) func(int) int {
    return func(j int) int {
        return f(i, j)
    }
}

func main() {
    var add Add = func(i, j int) int { return i + j }
    add3 := add.Apply(3)
    fmt.Println("add 3 to 2:", add3(2))
}

You can even try with variadic functions:

package main

import "fmt"

type Multiply func(...int) int

func (f Multiply) Apply(i int) func(...int) int {
    return func(values ...int) int {
        values = append([]int{i}, values...)
        return f(values...)
    }
}

func main() {
    var multiply Multiply = func(values ...int) int {
        var total int = 1
        for _, value := range values {
            total *= value
        }
        return total
    }


    var times2 Multiply = multiply.Apply(2)
    fmt.Println("times 2:", times2(3, 4), "(expect 24)")

    // ... and you can even cascade (if assigned the Multiply type)
    times6 := times2.Apply(3)
    fmt.Println("times 6:", times6(2, 3, 5, 10), "(expect 1800)")
}

Hope this helps!

like image 6
Andrea Funtò Avatar answered Nov 03 '22 16:11

Andrea Funtò