Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
package main
import (
"fmt"
"log"
)
// Product monoid
var identity int = 1
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}
product := identity
for _, n := range numbers {
product = mappend(product, n)
}
fmt.Printf("The product of %v is %d\n", numbers, product)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment