Skip to content

Instantly share code, notes, and snippets.

@nobonobo
Created March 10, 2017 05:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nobonobo/6f1a5c47cb86b382fe354f2dcd702e99 to your computer and use it in GitHub Desktop.
Save nobonobo/6f1a5c47cb86b382fe354f2dcd702e99 to your computer and use it in GitHub Desktop.
Goでfold実装
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 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
}
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)
}
@nobonobo
Copy link
Author

nobonobo commented Mar 10, 2017

ビルド

go get github.com/cheekybits/genny
go generate
go build .

出力

15(type:int)
foo, bar, baz(type:string)

@nobonobo
Copy link
Author

nobonobo commented Mar 10, 2017

この事例に限るのかもしれませんが、他の方法に比べ
非常に明瞭かつ簡潔にかけて、オーバーヘッドが少なく、コンパイル時に型チェックされ型安全です。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment