a talk about scala
JavaScript Scala Shell
Switch branches/tags
Nothing to show
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
theme
.gitignore
BUILD.txt
README.md
dog.jpeg
dog2.jpeg
examples.scala
family.scala
frisbee2.jpg
inverses.png
inverses.svg
landslide.sh
pattern-tricks.md
pattern.scala
presentation.html
realcode.txt
relationships.png
relationships.svg
sbt-launch.jar

README.md

[Stupid] Pattern Matching Tricks

Trick

Arnold deVos

@a4dev
adv-contact-trick@langdale.com.au

This is pattern matching:

case class Song( n: Int, thing: String)
val s = Song( 10, "green bottles")

val Song(10, x) = s
val y = s match { case Song(10, thing) => thing }
val z = for( Song(10, thing) <- Some(s) ) yield thing 

This is a partial function:

val pf: PartialFunction[Song, String] = { 
  case Song(10, thing) => thing 
  case Song(_, thing) => thing + ", but not 10 of them"
}

val a = pf(s)

Here is an extractor:

object ExtractCount {
  def unapply(s: Song) = Some(s.n)
}

val b = s match { case ExtractCount(n) => n + " things" }

Here is an optional function:

object countOption extends (Song => Option[Int]) {
  def apply(s: Song) = Some(s.n)
}
   
val c = countOption(s) map { _ + " things" } getOrElse { throw new MatchError(s) }

Different forms, convertable:

relationships


Equipment needed:

frisbee patent

class Extractor[A,B]( f: A => Option[B] ) { 
  def unapply( a: A ) = f(a) 
}

Equipment needed:

retriever

def pattern[B](pf: PartialFunction[Name,B]) = 
  new Extractor(pf.lift)

Onto the tricks ...

The example data is in family.scala

The pattern operators/DSL/whatever including the magical '&' operator are in pattern.scala

The tricks in action are in examples.scala


Come again?

http://notes.langdale.com.au

(A blog post about this.)