Home >Backend Development >Golang >How can you achieve functional programming's 'currying' in Go?

How can you achieve functional programming's 'currying' in Go?

DDD
DDDOriginal
2024-11-08 17:22:021035browse

How can you achieve functional programming's

Curry in Go: A Comprehensive Explanation

Question:

In functional programming languages like Haskell, it's possible to "curry" a function, allowing it to be partially applied and return another function that takes the remaining arguments. How can this be achieved in Go?

Answer:

Partial Application in Go

Go does not natively support partial application. However, you can achieve a similar effect using closures:

import "fmt"

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

func main() {
    add2 := mkAdd(2) // Creates a function that adds 2 to its argument
    fmt.Println(add2(5)) // Prints 7
}

Function Currying in Go

In Go, currying can be achieved using closures that accept multiple arguments and return a new function.

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)) // Prints 10
    fmt.Println(add3(6)) // Prints 9
}

Limitations:

The function mkAdd in the above example can only be partially applied from the left (i.e., the first argument). To support arbitrary partial application, you can use the following approach:

type Curry func(args ...int) func(args ...int) int

func (c Curry) Apply(args ...int) int {
    return c(args...)
}

func mkAdd(a int) Curry {
    return func(args ...int) func(args ...int) int {
        return func(moreArgs ...int) int {
            return a + append(args, moreArgs...)...
        }
    }
}

func main() {
    add2 := mkAdd(2).Apply(5, 3) // Partially apply 2 arguments
    fmt.Println(add2.Apply(6)) // Apply the remaining argument
}

The above is the detailed content of How can you achieve functional programming's 'currying' in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn