Created
February 9, 2018 05:18
-
-
Save desmondrawls/e28582c09c258374edb11cc5d60edf96 to your computer and use it in GitHub Desktop.
Bad Golang Monads
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"errors" | |
"fmt" | |
"strings" | |
) | |
func main() { | |
fmapOutcome, err := fmap(getName, isValidName)() | |
fmt.Print("fmap valid: ", fmapOutcome, "\n") | |
fmt.Print("fmap error: ", err, "\n") | |
bindOutcome, err := bind(getName, pure(isValidName))() | |
fmt.Print("bind valid: ", bindOutcome, "\n") | |
fmt.Print("bind error: ", err, "\n") | |
} | |
func getName() (string, error) { | |
apiCall := 4 | |
if apiCall > 3 { | |
return "Elizabeth McDoodle", nil | |
} else if apiCall > 2 { | |
return "Liz", nil | |
} else { | |
return "", errors.New("apis are hard, ok!") | |
} | |
} | |
func isValidName(name string) bool { | |
return strings.Contains(name, "McDoodle") | |
} | |
func bind(g func() (string, error), f func(string) (bool, error)) func() (bool, error) { | |
return func() (bool, error) { | |
a, err := g() | |
if err != nil { | |
return false, err | |
} | |
return f(a) | |
} | |
} | |
func pure(f func(string) bool) func(string) (bool, error) { | |
return func(somestring string) (bool, error) { | |
return f(somestring), nil | |
} | |
} | |
func fmap(g func() (string, error), f func(string) bool) func() (bool, error) { | |
return func() (bool, error) { | |
a, err := g() | |
if err != nil { | |
return false, err | |
} | |
b := f(a) | |
return b, nil | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment