From e4dc35ec742a0e93d148a5048de5f24a14eff4d2 Mon Sep 17 00:00:00 2001 From: "jian.han" Date: Thu, 11 Jan 2018 15:19:31 +1000 Subject: [PATCH] first class function example --- functions/first_class/main.go | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 functions/first_class/main.go diff --git a/functions/first_class/main.go b/functions/first_class/main.go new file mode 100644 index 0000000..5616572 --- /dev/null +++ b/functions/first_class/main.go @@ -0,0 +1,32 @@ +package main + +import "github.com/davecgh/go-spew/spew" + +type Cruncher func(int) int + +func mul(n int) int { + return n * 2 +} + +func add(n int) int { + return n + 100 +} + +func sub(n int) int { + return n - 1 +} + +func crunch(nums []int, a ...Cruncher) (rnums []int) { + rnums = append(rnums, nums...) + for _, f := range a { + for i, n := range rnums { + rnums[i] = f(n) + } + } + return +} + +func main() { + nums := []int{1, 2, 3, 4, 5, 6} + spew.Dump(crunch(nums, mul, add, sub)) +}