2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2019-04-17

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

// 関数に名前付き型を定義する
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
}
2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?