Created
April 15, 2021 00:52
-
-
Save pedrofurla/ab47df2ab121bb0dc877dbc394e03887 to your computer and use it in GitHub Desktop.
Vectors Haskell and Scala
This file contains hidden or 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
module Vector where | |
data Vector = Vector Int Int | |
add (Vector x0 y0) (Vector x1 y1) = Vector (x0+x1) (y0+y1) | |
inverse (Vector x0 y0) = Vector (-x0) (-y0) | |
subtract v0 = add v0 . inverse | |
-- the above is equivalent to `subtract v0 v1 = add v0 (inverse v1) |
This file contains hidden or 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
object Vector { // This is like a namespace | |
case class Vector(x:Int, y:Int) { | |
def add(r:Vector) = r match { | |
case Vector(x1, y1) => Vector(x+x1, y+y1) | |
} | |
def inverse = Vector(-x, -y) | |
def substract(r:Vector) = add(r.inverse) | |
} | |
def examples = { | |
val topRight = Vector(1,1) | |
val topLeft = Vector(-1,1) | |
assert(topRight.add(topLeft) == Vector(0,2)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment