Last active
October 15, 2015 20:22
-
-
Save groveriffic/3973c9321a82d571e07e to your computer and use it in GitHub Desktop.
Demonstrates a trivial sum monoid in Go.
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 ( | |
"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