fork download
  1. package main
  2.  
  3. import "fmt"
  4.  
  5. type TransformerFunction func(int) int
  6.  
  7. func NewCompositeTransformer(f, g TransformerFunction) TransformerFunction {
  8. return func(x int) int {
  9. return f(g(x))
  10. }
  11. }
  12.  
  13. func Compose(f, g TransformerFunction, fs ...TransformerFunction) TransformerFunction {
  14. composite := NewCompositeTransformer(f, g)
  15.  
  16. for _, f := range fs {
  17. composite = NewCompositeTransformer(composite, f)
  18. }
  19.  
  20. return composite
  21. }
  22.  
  23. func double(x int) int {
  24. return 2 * x
  25. }
  26.  
  27. func inc(x int) int {
  28. return x + 1
  29. }
  30.  
  31. func square(x int) int {
  32. return x * x
  33. }
  34.  
  35. func main() {
  36. doubleThenIncThenSquare := Compose(square, inc, double)
  37. fmt.Println(doubleThenIncThenSquare(4))
  38. }
Success #stdin #stdout 0.01s 5284KB
stdin
Standard input is empty
stdout
81