Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
package main
import (
"fmt"
"log"
)
// String Concatenation Monoid
var identity string = ""
var mappend = func(a, b string) string {
return a + b
}
func main() {
// s could be replaced with any value of type string
s := "foo"
identityVerified := mappend(identity, s) == s && mappend(s, identity) == s
if !identityVerified {
log.Fatal("invalid identity")
}
// a, b, and c could be any values of our given type
a := "foo"
b := "bar"
c := "baz"
associativityVerified := mappend(mappend(a, b), c) == mappend(a, mappend(b, c))
if !associativityVerified {
log.Fatal("not associative")
}
fmt.Println("You've got a monoid")
strings := []string{"Hello", " Gophers!",
" Can", " I", " sell", " you",
" some", " monoids?"}
concatenated := identity
for _, s := range strings {
concatenated = mappend(concatenated, s)
}
fmt.Println(concatenated)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment