Help us understand the problem. What is going on with this article?

Golangでメソッド呼び出しによる部分適用

出来ないかなーと思いつつ遊んでいたら出来たのでメモ。

// 関数に名前付き型を定義する
type Add func(int, int) int

// 上で定義したAdd型に部分適用するメソッドを定義
func (f Add) apply(applyValue int) func(int) int {
    return func(value int) int {
        return f(value, applyValue)
    }
}

// Add型と同じ型を持つ関数を定義
func add(a, b int) int {
    return a + b
}

func main() {
    // 関数addがAdd型として扱えるように変数に格納する
    var f Add = add

    // Add型であるfからはapplyメソッドが呼び出せる
    f2 := f.apply(2)

    // 部分適用した関数f2は引数が一つで呼び出せるようになる
    fmt.Print(f2(1)) // 3
}

このような方法を取らなくても、以下のような部分適用する関数を定義すればいいだけなので無性にメソッド呼び出ししたくなった時に利用するといいでしょう。

func add(a, b int) int {
    return a + b
}

func apply(f func(int, int) int, applyValue int) f(int) int {
    return func(value int) int {
        return f(value, applyValue)
    }
}

func main() {
    add2 := apply(add, 2)
    fmt.Print(add2(1)) // 3
}
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away