Skip to content

Instantly share code, notes, and snippets.

@ghthor
Last active August 29, 2015 14:13
Show Gist options
  • Select an option

  • Save ghthor/07381f5a2ced08305724 to your computer and use it in GitHub Desktop.

Select an option

Save ghthor/07381f5a2ced08305724 to your computer and use it in GitHub Desktop.
Playing with monads in go. Trying to understand what they are.
package main
import (
"fmt"
"strings"
)
type stringMonad func(string) (string, error)
func removeString(s string) stringMonad {
return func(data string) (string, error) {
i := strings.Index(data, s)
if i == -1 {
return data, fmt.Errorf(`string "%s" doesn't contain "%s"`, data, s)
}
return data[:i] + data[i+len(s):], nil
}
}
func appendString(s string) stringMonad {
return func(data string) (string, error) {
return data + s, nil
}
}
type with string
func replaceString(s string, w with) stringMonad {
return func(data string) (string, error) {
i := strings.Index(data, s)
if i == -1 {
return data, fmt.Errorf(`string "%s" doesn't contain "%s"`, data, s)
}
return strings.Replace(data, s, string(w), -1), nil
}
}
func doStr(s string, ops []stringMonad) string {
for _, op := range ops {
s, _ = op(s)
}
return s
}
func mustDoStr(s string, ops []stringMonad) (string, error) {
var err error
for _, op := range ops {
s, err = op(s)
if err != nil {
return s, err
}
}
return s, err
}
func main() {
s := doStr("the bcaon had lots of grease", []stringMonad{
removeString("grease"),
appendString("flavor"),
appendString("."),
replaceString("bcaon", with("bacon")),
replaceString("pig", with("sheep")),
})
fmt.Println(s)
s, err := mustDoStr("the bcaon had lots of grease", []stringMonad{
removeString("grease"),
appendString("flavor"),
appendString("."),
replaceString("bcaon", with("bacon")),
replaceString("pig", with("sheep")),
})
if err != nil {
fmt.Println(err)
} else {
fmt.Println(s)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment