Last active
October 20, 2015 22:23
-
-
Save groveriffic/b74e4255bb23d8313123 to your computer and use it in GitHub Desktop.
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" | |
) | |
type point struct { | |
x int | |
y int | |
} | |
// we can think of a 2D translation as moving the origin to a new point | |
// so a translation is defined by a point | |
type translation point | |
var identity = translation{} | |
func mappend(a, b translation) translation { | |
return translation{x: a.x + b.x, y: a.y + b.y} | |
} | |
func (t translation) apply(p point) point { | |
return point{x: t.x + p.x, y: t.y + p.y} | |
} | |
func main() { | |
// n could be replaced with any value of our type | |
n := translation{x: 42, y: 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 := translation{x: 1, y: 15} | |
b := translation{x: 9, y: -20} | |
c := translation{x: 40, y: 2} | |
associativityVerified := mappend(mappend(a, b), c) == mappend(a, mappend(b, c)) | |
if !associativityVerified { | |
log.Fatal("not associative") | |
} | |
fmt.Println("You've got a monoid") | |
t := mappend(a, b) | |
t = mappend(t, c) | |
p := t.apply(point{x: 10, y: 10}) | |
message := "After appending our translations and applying them,\n" + | |
"our point moved from (10, 10) to (%d, %d)\n" | |
fmt.Printf(message, p.x, p.y) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment