These are the slides from my GopherCon 2017 Talk.
Viewed as a set of design patterns, we can apply functional programming concepts to Go code to get simpler, more modular code. I'll eschew most of the FP theory and show some of these concepts and patterns in real code. I'll also show how small, local bits of "functionalization" can lead to large improvements over time.
3. Gopher @ Microsoft (formerly Deis)
Co-lead, Kubernetes SIG-Service-Catalog
Former Scala purist
Current FP student, F# & Haskell Tinkerer
I like to teach
A Bit More About Me
4. FP & Go: Is This Even A Good Idea?
I think so!
Go won’t be the next Haskell any time soon
But these FP concepts are still powerful when applied appropriately
5.
6. Today Is About...
Adding tools to your toolbox
A new perspective
Applying new (useful) abstractions to your code
7.
8. ...a style of building the structure and elements
of computer programs—that treats
computation as the evaluation of
mathematical functions and avoids
changing-state and mutable data
https://en.wikipedia.org/wiki/Functional_programming
15. Pure Functions
Only operate on the parameters; no side effects
Predictable, easy to reason about
But, you have to do real things!
16. Let’s Rewrite! Starting With A Refresher…
// In case you forgot, this type is from net/http.
// Looks the same as the function signature of myHandler!
type HandlerFunc func(http.ResponseWriter, *http.Request)
17. Let’s Rewrite, For Real This Time!
func myHandler(db *sql.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
res, err := db.Exec(...)
// …
}
}
21. Transforming a Slice, The FP Way
ints := getIntSlice()
results := magical(ints).Map(doSomething)
22. magical() makes a Functor
… and a Functor is a:
- Go struct that contains the data (i.e. a slice)
- Map function that operates on the container
Map(fn func(int) int) IntSliceFunctor
29. Optional
A “container” that either has an element, or does not
Still has Map, also has an “escape hatch”
Map(fn func(int) int) OptionalIntFunctor
Int() int // escape hatch
39. Bonus Round! Equality Checks With Type Classes
Very similar to interfaces, just a new way to think about them. Neither of
these compile:
“1” == 1
[]int{1, 2, 3} == []int{1, 2, 3}
https://github.com/go-functional/core/blob/master/examples/typeclass/eq/m
ain.go