Created
March 10, 2017 05:54
-
-
Save nobonobo/6f1a5c47cb86b382fe354f2dcd702e99 to your computer and use it in GitHub Desktop.
Goでfold実装
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
//go:generate genny -in=$GOFILE -out=gen-$GOFILE gen "Type=string,int" | |
import ( | |
"github.com/cheekybits/genny/generic" | |
) | |
type Type generic.Type | |
func FoldType(l []Type, apply func(a Type, b Type) Type) (res Type) { | |
res = l[0] | |
for _, v := range l[1:] { | |
res = apply(res, v) | |
} | |
return res | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This file was automatically generated by genny. | |
// Any changes will be lost if this file is regenerated. | |
// see https://github.com/cheekybits/genny | |
package main | |
func FoldString(l []string, apply func(a string, b string) string) (res string) { | |
res = l[0] | |
for _, v := range l[1:] { | |
res = apply(res, v) | |
} | |
return res | |
} | |
func FoldInt(l []int, apply func(a int, b int) int) (res int) { | |
res = l[0] | |
for _, v := range l[1:] { | |
res = apply(res, v) | |
} | |
return res | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
func main() { | |
list := []int{1, 2, 3, 4, 5} | |
res := FoldInt(list, func(a int, b int) int { return a + b }) | |
fmt.Printf("%[1]d(type:%[1]T)\n", res) | |
slist := []string{"foo", "bar", "baz"} | |
sres := FoldString(slist, func(a string, b string) string { return a + ", " + b }) | |
fmt.Printf("%[1]s(type:%[1]T)\n", sres) | |
} |
この事例に限るのかもしれませんが、他の方法に比べ
非常に明瞭かつ簡潔にかけて、オーバーヘッドが少なく、コンパイル時に型チェックされ型安全です。
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ビルド
go get github.com/cheekybits/genny go generate go build .
出力