Skip to content

Instantly share code, notes, and snippets.

@hossshy
Created January 22, 2016 03:11
Show Gist options
  • Save hossshy/55c6ef6d43d69adf36cf to your computer and use it in GitHub Desktop.
Save hossshy/55c6ef6d43d69adf36cf to your computer and use it in GitHub Desktop.
package chapter5
/**
* Created by hoshi on 1/22/16.
*/
object MainObj2 {
def main(args: Array[String]) {
// a pattern match down to a PartialFunction[A,B]
val list = List("A", 2, 3, "D")
var tmp = list.filter(a => a match {
case s: String => true
case _ => false
})
println(tmp)
// It reduces this code snippet
tmp = list.filter {
case s: String => true
case _ => false
}
println(tmp)
// Pattern Matching As Functions
def handleRequest(req: List[String])(exceptions: PartialFunction[List[String], String]): String =
if ( exceptions.isDefinedAt(req) ) exceptions(req) else "Handling URL " + req + " in the normal way"
def doApi(call: String, params: List[String]): String = "Doing API call " + call
println("foo " + handleRequest("foo" :: Nil) {
case "api" :: call :: params => doApi(call, params)
})
val f1: PartialFunction[List[String], String] = {
case "stuff" :: Nil => "Got some stuff"
}
val f2: PartialFunction[List[String], String] = {
case "other" :: params => "Other:" + params
}
val f3 = f1 orElse f2
println("F3 " + handleRequest("other" :: "b" :: Nil)(f3))
println("F3 " + handleRequest("stuff" :: Nil)(f3))
}
}
----
package chapter5
/**
* Object-Oriented and Functional Tensions
*/
case class Circle(radius: Double) extends Shape
case class Square(length: Double) extends Shape
case class Rectangle(h: Double, w: Double) extends Shape
class Shape {}
object ShapeMain extends App {
// It's easy to add common functions
def area(shape: Shape): Double = shape match {
case Circle(r) => r * r * Math.PI
case Square(l) => l * l
case Rectangle(h, w) => h * w
}
val c = Circle(5)
val s = Square(4)
val r = Rectangle(3, 2)
println(area(c))
println(area(s))
println(area(r))
}
----
package chapter5
/**
* Example of visitor pattern with pattern-matching version
* No need "accept" method
*/
trait CarElement
case class Wheel(name: String) extends CarElement
case class Engine() extends CarElement
case class Body() extends CarElement
case class Car(elements: List[CarElement]) extends CarElement
object CarElementMain {
def doSomething(in: CarElement): Unit = in match {
case Wheel(name) => println(s"W $name")
case Engine() => println("E")
case Body() => println("B")
case Car(e) => e.foreach(doSomething)
}
def main(args: Array[String]) {
val elems = Car(List(new Engine, new Body, new Wheel("FR"), new Wheel("FL")))
doSomething(elems)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment