Slide 1

Slide 1 text

Functional Go

Slide 2

Slide 2 text

Why would you do that?

Slide 3

Slide 3 text

quicksort [] = [] quicksort (x:xs) = let smaller = quicksort [a | a <- xs, a <= x] bigger = quicksort [a | a <- xs, a > x] in smaller ++ [x] ++ bigger Quicksort in Haskell

Slide 4

Slide 4 text

Live coding Andrew Sorensen Keynote at OSCON

Slide 5

Slide 5 text

What is functional programming?

Slide 6

Slide 6 text

Functional programming - no mutable state - functions as first class objects

Slide 7

Slide 7 text

No mutable state - simply a choice - no for loops

Slide 8

Slide 8 text

func SumI(vs []int) int { s := 0 for _, v := range vs { s += v } return v } Iterative sum

Slide 9

Slide 9 text

func SumI(vs []int) int { s := 0 for _, v := range vs { s += v } return v } Iterative fun is not functional

Slide 10

Slide 10 text

func SumR(vs []int) int { if len(vs) == 0 { return 0 } return vs[0] + Sum(vs[1:]) } Recursive sum

Slide 11

Slide 11 text

Is it fast? PASS BenchmarkSumI-4 3000000 462 ns/op BenchmarkSumR-4 300000 4707 ns/op

Slide 12

Slide 12 text

func SumTR(vs []int, s int) int { if len(vs) == 0 { return s } return Sum(vs[1:], s + vs[0]) } Tail recursion

Slide 13

Slide 13 text

PASS BenchmarkSumI-4 3000000 462 ns/op BenchmarkSumR-4 300000 4707 ns/op BenchmarkSumTR-4 300000 5056 ns/op Is it fast?

Slide 14

Slide 14 text

func SumTRG(vs []int, s int) int { begin: if len(vs) == 0 { return s } vs, s = vs[1:], s + vs[0] goto begin } Tail recursion with faked optimization

Slide 15

Slide 15 text

PASS BenchmarkSumI-4 3000000 462 ns/op BenchmarkSumR-4 300000 4707 ns/op BenchmarkSumTR-4 300000 5056 ns/op BenchmarkSumTRG-4 1000000 1587 ns/op Is it fast?

Slide 16

Slide 16 text

This is not about the speed, clearly

Slide 17

Slide 17 text

Functions are first class objects - as parameters - as returned values - in Go they can be used anywhere!

Slide 18

Slide 18 text

Functions applied on functions - map, filter, fold, etc High order functions

Slide 19

Slide 19 text

map ( ) → [ ] → [ ]

Slide 20

Slide 20 text

( ) → [ ] → [ ] = int = bool

Slide 21

Slide 21 text

func Map(f func(v int) bool, vs []int) []bool { if len(vs) == 0 { return nil } return append( []bool{f(vs[0])}, Map(f, vs[1:])...) } Map on concrete types

Slide 22

Slide 22 text

func Map(f func(v int) bool, vs []int) []bool { if len(vs) == 0 { return nil } return append( Map(f, vs[:len(vs)-1]), vs[len(vs)-1]) } Map on concrete types (reversed order)

Slide 23

Slide 23 text

func main() { isEven := func(v int) bool { return v%2 == 0 } nums := []int{1, 2, 3, 4, 5, 6} fmt.Println(Map(isEven, nums)) // [false true false true false true] } Map on concrete types

Slide 24

Slide 24 text

template< , > func Map(f func(a ) , vs [] ) [] If Go had generics

Slide 25

Slide 25 text

func(a ) ⇒ interface{} [] ⇒ interface{} [] ⇒ interface{} But it doesn’t

Slide 26

Slide 26 text

func Map(f interface{}, vs interface{}) interface{}

Slide 27

Slide 27 text

func Map(f interface{}, vs interface{}) interface{}

Slide 28

Slide 28 text

“embrace the interface” but not too much

Slide 29

Slide 29 text

func Map(f interface{}, vs interface{}) interface{}

Slide 30

Slide 30 text

Representing functions type Func struct { in reflect.Type out reflect.Type f func(interface{}) interface{} } func (f Func) Call(v interface{}) interface{} { return f.f(v) }

Slide 31

Slide 31 text

func NewFunc(f interface{}) (*Func, error) { // check type of f and return an error if needed return &Func{ in: tf.In(0), out: tf.Out(0), f: func(x interface{}) interface{} { out := vf.Call([]reflect.Value{reflect.ValueOf(x)}) return out[0].Interface() }, }, nil } Representing functions: NewFunc

Slide 32

Slide 32 text

func Must(f *Func, err error) *Func { if err != nil { panic(err) } return f } Representing functions: Must

Slide 33

Slide 33 text

func Map(f interface{}, vs interface{}) interface{} func Map(f *Func, vs interface{}) interface{}

Slide 34

Slide 34 text

func Map(f *Func, vs interface{}) interface{}

Slide 35

Slide 35 text

type List struct { Head interface{} Tail *List } func Map(f *Func, l *List) *List { if l == nil { return nil } return &List{f.Call(l.Head), Map(f, l.Tail)} } A simple List

Slide 36

Slide 36 text

Should this be a method? Of what?

Slide 37

Slide 37 text

func (l *List) Map(f *Func) *List { if l == nil { return nil } return &List{ f.Call(l.Head), Map(f, l.Tail), } } Map in Go, as a method of List

Slide 38

Slide 38 text

toUpper := Must(NewFunc(strings.ToUpper)) m := &List{“hello”, &List{“bye”, nil}} res := m.Map(toUpper) fmt.Println(res) // “HELLO”, “BYE” Using map

Slide 39

Slide 39 text

typeclasses: an interlude

Slide 40

Slide 40 text

The Show typeclass class Show a where show :: a -> String

Slide 41

Slide 41 text

type Stringer interface { String() string } The Stringer interface

Slide 42

Slide 42 text

The Eq typeclass class Eq a where (==) :: a -> a -> Bool (/=) :: a -> a -> Bool

Slide 43

Slide 43 text

type Equatable interface { Equals(e Equatable) bool } satisfied by an Integer type func (i Integer) Equals(j Integer) bool The Equatable interface

Slide 44

Slide 44 text

typeclasses are “like” interfaces

Slide 45

Slide 45 text

What else can we map over?

Slide 46

Slide 46 text

Lists Maps Trees … What can we map over?

Slide 47

Slide 47 text

func (l *List) Map(f *Func) *List type Mapper interface { Map(*Func) ??? } Mapper interface

Slide 48

Slide 48 text

class Functor f a where fmap :: (a -> b) -> f a -> f b Functor typeclass

Slide 49

Slide 49 text

fmap ( ) → ( ) → ( )

Slide 50

Slide 50 text

A couple of useful functors

Slide 51

Slide 51 text

maybe

Slide 52

Slide 52 text

type Maybe struct { Value interface{} } func (m Maybe) Map(f *Func) Maybe { if m.Value == nil { return Maybe{} } return Maybe{ f.Call(m.Value) } } Maybe

Slide 53

Slide 53 text

Once we create a Func: toUpper := Must(NewFunc(strings.ToUpper)) We can call it with a value: m := Maybe{“hello”} res := m.Map(toUpper) fmt.Println(res.Value) // “HELLO” Maybe

Slide 54

Slide 54 text

Once we create a Func: toUpper := Must(NewFunc(strings.ToUpper)) Or without it: m := Maybe{} res := m.Map(toUpper) fmt.Println(res.Value) // Maybe

Slide 55

Slide 55 text

toUpper := Must(NewFunc(strings.ToUpper)) twice := Must(NewFunc(func(s string) string { return s+s })) m := Maybe{“hello”} res := m.Map(toUpper).Map(twice) fmt.Println(res.Value) // “HELLOHELLO” Maybe chained

Slide 56

Slide 56 text

An actual use case → → →⛅ person address city weather

Slide 57

Slide 57 text

type Person struct{ address *Address } type Address struct{ city *City } type City struct{ weather *Weather } type Weather struct{ desc string } func (p Person) Address() *Address { return p.address } func (a Address) City() *City { return a.city } func (c City) Weather() *Weather { return c.weather } func (w Weather) Desc() string { return w.desc } An actual use case

Slide 58

Slide 58 text

func (p Person) Weather() string { a := p.Address() if a == nil { return “no weather” } c := a.City() if c == nil { return “no weather” } w := c.Weather() if w == nil { return “no weather” } return w.Description() } An actual use case

Slide 59

Slide 59 text

func (p Person) Weather() string { m := Maybe{p}. Map(Must(NewFunc(func(p Person) *Address { return p.address }))). Map(Must(NewFunc(func(a Address) *City { return a.city }))). ... Maybe chained

Slide 60

Slide 60 text

We can obtain a function from a value: var p Person p.Address // func() *Address Or from a type Person.Address // func(Person) *Address Method values

Slide 61

Slide 61 text

func (p Person) Weather() string { w := Maybe{p}. Map(Must(NewFunc(Person.Address))). Map(Must(NewFunc(Address.City))). Map(Must(NewFunc(City.Weather))). Map(Must(NewFunc(Weather.Description))) if w.Value == nil { return “no weather” } return w.Value.(string) } Maybe chained

Slide 62

Slide 62 text

func (m Maybe) Do(fs ...interface{}) (Maybe, error) { if len(fs) == 0 { return m, nil } f, err := NewFunc(fs[0]) if err != nil { return Maybe{}, err } return m.Map(f).Do(fs[1:]...) } Chaining map with Maybe.Do

Slide 63

Slide 63 text

func (p Person) Weather() string { w := Maybe{p}.Do( Person.Address, Address.City, City.Weather, Weather.Description) if w.Value == nil { return “no weather” } return w.Value.(string) } Chaining map with Maybe.Do

Slide 64

Slide 64 text

many

Slide 65

Slide 65 text

type Many struct { Head interface{} Tail *Many } Many

Slide 66

Slide 66 text

func (m *Many) Map(f *Func) *Many { if m == nil { return nil } res := m.Tail.Map(f) // append all elements from the result for _, v := range toSlice(f.Call(m.Head)) { r = &Many{v, res} } return res } Many

Slide 67

Slide 67 text

Once we create a Func: toUpper := Must(NewFunc(strings.ToUpper)) We can call it with a value: m := Many{“hello there”, “good bye”} res := m.Map(toUpper) fmt.Println(res.Value) // “HELLO THERE”, “GOOD BYE” Many

Slide 68

Slide 68 text

If we have a new function: toUpper := Must(NewFunc(strings.ToUpper)) fields := Must(NewFunc(strings.Fields)) Or without it: m := Many{“hello there”, “good bye”} res := m.Map(toUpper).Map(fields) fmt.Println(res.Value) // “HELLO”, “THERE”, “GOOD”, “BYE” Many chained

Slide 69

Slide 69 text

An actual use case → → →〰 library books pages lines

Slide 70

Slide 70 text

type Library struct{ books []Book } type Book struct{ pages []Page } type Page struct{ lines []Line } type Line struct{ text string } func (l Library) Books() []Book { return l.books } func (b Book) Pages() []Page { return b.pages } func (p Page) Lines() []Line { return p.lines } func (l Line) Text() string { return l.text } An actual use case

Slide 71

Slide 71 text

An actual use case words := make(map[string]int) for _, b := range l.Books() { for _, p := range b.Pages() { for _, l := range p.Lines() { for _, word := range strings.Fields(l.Text()) { words[word]++ } } } }

Slide 72

Slide 72 text

NewMany(l). Map(Must(NewFunc(Library.Books))). Map(Must(NewFunc(Book.Pages))). Map(Must(NewFunc(Page.Lines))). Map(Must(NewFunc(Line.Text))). Map(Must(NewFunc(strings.Fields))). Map(Must(NewFunc(func(s string) bool { count[s]++; return true }))) Many chained

Slide 73

Slide 73 text

Many Do _, err := NewMany(m).Do( Library.Books, Book.Pages, Page.Lines, Line.Text, strings.Field, func(s string) bool { count[s]++; return true }) if err != nil { // type error }

Slide 74

Slide 74 text

Many Do w, err := NewMany(m). Do( Library.Books, Book.Pages, Page.Lines, Line.Text, strings.Field) if err != nil { // type error } w.Each(func(s string) { count[s]++ })

Slide 75

Slide 75 text

Functional Go - Doable - but slower than normal code - requires reflection - Inspiration for good APIs - functors to abstract function application - what could we do with monads?

Slide 76

Slide 76 text

@francesc Merci

Slide 77

Slide 77 text

Composition of functions func Compose(f, g *Func) (*Func, error) { if g.out != f.in { return nil, fmt.Errorf("can't compose: %v != %v", g.out, f.in) } return &Func{ g.in, f.out, func(x interface{}) interface{} { return f.Call(g.Call(x)) }, }, nil }

Slide 78

Slide 78 text

func (m Maybe) Map(f *Func) Maybe { if m.Value == nil { return Maybe{} } r := f.Call(m.Value) vr := reflect.ValueOf(r) if vr.Kind() == reflect.Ptr && vr.IsNil() { return Maybe{} } return Maybe{r} } Mapping over a Maybe and handling nil pointers