How to compose functions in go?

Viewed 1176

I'm trying to figure out how to set up middlewares, and right now I've got something like:

func applyMiddleware(h *Handle) *Handle {
   return a(b(c(h)))
}

Is there a way to "compose" these functions so I can just pass a list of Handle(s) and it will return the composed function?

1 Answers

use a slice

https://play.golang.org/p/DrEnGkIEbU3

package main

import (
    "fmt"
)

func main() {
    fmt.Println(v(v(v(0))))
    fmt.Println(compose(v, v, v)(0))
}
func v(i int) int {
    return i + 1
}
func compose(manyv ...func(int) int) func(int) int {
    return func(i int) int {
        for _, v := range manyv {
            i = v(i)
        }
        return i
    }
}
Related