mirror of
https://github.com/crazybber/awesome-patterns.git
synced 2024-11-25 06:16:03 +03:00
first class function example
This commit is contained in:
parent
d5514795f0
commit
e4dc35ec74
32
functions/first_class/main.go
Normal file
32
functions/first_class/main.go
Normal file
@ -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))
|
||||
}
|
Loading…
Reference in New Issue
Block a user