github.com/l3x/learn-fp-go@v0.0.0-20171228022418-7639825d0b71/2-design-patterns/ch04-solid/01_lambda/main.go (about) 1 package main 2 3 import "fmt" 4 5 type Collection []string 6 type MapFunc func(string) string 7 type MapFunc2 func(string, int) string 8 9 func (cars Collection) Map(fn MapFunc) Collection { 10 mappedCars := make(Collection, 0, len(cars)) 11 for _, car := range cars { 12 mappedCars = append(mappedCars, fn(car)) 13 } 14 return mappedCars 15 } 16 func (cars Collection) Map2(fn MapFunc2) Collection { 17 mappedCars := make(Collection, 0, len(cars)) 18 for _, car := range cars { 19 mappedCars = append(mappedCars, fn(car, 2)) 20 } 21 return mappedCars 22 } 23 24 func Upgrade() MapFunc { 25 return func(car string) string { 26 return fmt.Sprintf("%s %s", car, "LX") 27 } 28 } 29 30 // For an explanation of what's going on below, see chapter 11. 31 type Func func(int) int 32 type FuncFunc func(Func) Func 33 type RecursiveFunc func (RecursiveFunc) Func 34 func yCombinator(f FuncFunc) Func { 35 g := func(r RecursiveFunc) Func { 36 return f(func(x int) int { 37 return r(r)(x) 38 }) 39 } 40 return g(g) 41 } 42 func fibFuncFunc(f Func) Func { 43 return func(x int) int { 44 if x == 0 { 45 return 0 46 } else if x <= 2 { 47 return 1 48 } else { 49 return f(x-2) + f(x-1) 50 } 51 } 52 } 53 54 func main() { 55 cars := &Collection{"Honda Accord", "Lexus IS 250"} 56 57 fmt.Println("Upgrade() is not a Lambda Expression:") 58 fmt.Printf("> cars.Map(Upgrade()): %+v\n\n", cars.Map(Upgrade())) 59 60 fmt.Println("Anonymous function is not a Lambda Expression:") 61 fmt.Printf("> cars.Map(func(...{...}): %+v\n\n", cars.Map2(func(car string, num int) string { 62 return fmt.Sprintf("%s %s%d", car, "LX", num) 63 })) 64 65 yCombo := yCombinator(fibFuncFunc) 66 fmt.Println("r(r)(x) in anonymous function in yCombinator is a Lambda Expression:") 67 fmt.Println("> yCombo(5):", yCombo(5)) 68 }