Skip to content

Instantly share code, notes, and snippets.

@rbonvall
Last active July 13, 2018 21:28
Show Gist options
  • Save rbonvall/8c2c6e31c0457d1b17ce18aaf1e322a4 to your computer and use it in GitHub Desktop.
Save rbonvall/8c2c6e31c0457d1b17ce18aaf1e322a4 to your computer and use it in GitHub Desktop.
Ejemplos meetup de Scala, 12 de julio de 2018
case class Point(x: Double, y: Double) {
def +(p: Point) = Point(x + p.x, y + p.y)
def *(a: Double) = Point(a * x, a * y)
def distTo(that: Point) = {
val Point(dx, dy) = this + that * -1
math.sqrt(dx * dx + dy * dy)
}
}
trait Shape
case class Circle(center: Point, radius: Double) extends Shape
case class Polygon(vertices: Seq[Point]) extends Shape {
def edges: Seq[(Point, Point)] =
(vertices.init zip vertices.tail) :+ (vertices.last, vertices.head)
// Pattern match to extract the points.
def perimeter: Double =
edges.map { case (p1, p2) ⇒ p1 distTo p2 }.sum
// Pattern match to extract xy coordinates.
def area: Double =
edges.map {
case (Point(x1, y1), Point(x2, y2)) ⇒ (x2 - x1) * (y2 + y1)
}.sum / 2
}
def name(p: Point): String = p match {
case Point(0, 0) ⇒ "origen"
case Point(x, y) ⇒ s"el punto $x $y"
}
val triangle = Polygon(List(Point(0, 0), Point(0, 4), Point(3, 4)))
val myShapes = List(
Circle(Point(3, 0), 5),
triangle,
Circle(triangle.vertices.head, 20)
)
assert(triangle.area == 6)
assert(triangle.perimeter == 12)
myShapes.map {
case Circle(Point(0, 0), r) ⇒ "Un circulo en el origen"
case Circle(c, r) if r < 10 ⇒ "Un circulo chico"
case Circle(c, r) ⇒ "Un circulo grande"
case Polygon(vs) ⇒ s"Un poligono de ${vs.length} lados"
}
val n = 20
List(11, 22, 33).map { x ⇒ 2 * x } // no es un closure
List(11, 22, 33).map { x ⇒ n * x } // sí es un closure (captura variables de afuera)
val persons = List("Alicia", "Bernardo", "Claudio")
val ns = List(66, 22, 77, 44, 22)
val hola = Stream.continually("Hola")
persons zip ns zip hola
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment