etorreborre / pattern_tricks

a talk about scala

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

[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 ...


Come again?

About

a talk about scala


Languages

Language:JavaScript 83.8%Language:Scala 15.9%Language:Shell 0.3%