Skip to content

Instantly share code, notes, and snippets.

@groveriffic
Last active Oct 15, 2015
Embed
What would you like to do?
Demonstrates a trivial sum monoid in Go.
package main
import (
"fmt"
"log"
)
// Sum monoid
var identity int = 0
var mappend = func(a, b int) int {
return a + b
}
func main() {
// n could be replaced with any value of type int
n := 42
identityVerified := mappend(identity, n) == n && mappend(n, identity) == n
if !identityVerified {
log.Fatal("invalid identity")
}
// a, b, and c could be any values of our given type
a := 1
b := 9
c := 40
associativityVerified := mappend(mappend(a, b), c) == mappend(a, mappend(b, c))
if !associativityVerified {
log.Fatal("not associative")
}
fmt.Println("You've got a monoid")
numbers := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
sum := identity
for _, n := range numbers {
sum = mappend(sum, n)
}
fmt.Printf("The sum of %v is %d\n", numbers, sum)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment