Skip to content

Instantly share code, notes, and snippets.

@pedrofurla
Created April 15, 2021 00:52
Show Gist options
  • Save pedrofurla/ab47df2ab121bb0dc877dbc394e03887 to your computer and use it in GitHub Desktop.
Save pedrofurla/ab47df2ab121bb0dc877dbc394e03887 to your computer and use it in GitHub Desktop.
Vectors Haskell and Scala
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)
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