2
2

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.

Goでカリー化とMapの実装

Posted at

食べられないほうのカリー化入門を読んで、「へえ、カリー化って面白そうじゃん。Go言語でも実装しやすそう」と思っていたのですが、Go言語で関数のカリー化(currying)入門で、先を越されてしまいました……

まあせっかくなので、食べられない方のカリー化でサンプルにしているような、配列操作のサンプルコードを晒してみます。

package main

import "fmt"

type Slice []int

func main() {
	sample := Slice{1, 3, -5, 7, -2}

	// n倍する関数を返す
	times := func(n int) func(int) int {
		return func(x int) int {
			return x * n
		}
	}

	// +nする関数を返す
	add := func(n int) func(int) int {
		return func(x int) int {
			return x + n
		}
	}

	// nと比べて小さければnを返す関数を返す
	max := func(n int) func(int) int {
		return func(x int) int {
			if n > x {
				return n
			} else {
				return x
			}
		}
	}

	fmt.Println("--- 実行 ---")
	fmt.Println(sample.Map(times(2)))
	fmt.Println(sample.Map(times(10)))
	fmt.Println(sample.Map(add(10)))
	fmt.Println(sample.Map(max(0)))
}

//スライスの各要素に対して指定の操作をする
func (s Slice) Map(proc func(int) int) []int {
	clone_s := make([]int, len(s))
	for i := range s {
		clone_s[i] = proc(s[i])
	}
	return clone_s
}
--- 実行 ---
[2 6 -10 14 -4]
[10 30 -50 70 -20]
[11 13 5 17 8]
[1 3 0 7 0]

割とさくっと実行できますな。

しかしgoでEach, Map, Selectのサンプルでも、近いことをしていました……!!

2
2
1

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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?