Lösungen: Extraktoren

  1. Wenn wir den Extraktor über eine Klasse erstellen können wir sein Verhalten anpassen.
    class Nth(n: Int) {
      def unapply(xs: Seq[Int]) = if (n < xs.size) Some(xs(n)) else None
    }
    val isSecond_? = new Nth(1)
    val isThird_? = new Nth(2)
    Vector(9, 13, 3, 73, 52) match {
      case isSecond_?(12) => println("second is twelve")
      case isThird_?(3) => println("third is three")
      case _ => println("nothing special found")
    }
    
  2. Der &-Extraktor ist sehr einfach. Es genügt, einfach einen Tuple2 mit dem Eingabestring zurückzugeben.
    object & {
      def unapply(a: String) = Some(a, a)
    }
    object StartsWith {
      def unapply(s: String) = s.headOption
    }
    object EndsWith {
      def unapply(s: String) = s.lastOption
    }
    
    "Hello World" match {
      case StartsWith('H') & EndsWith('d') => "yes"
      case _ => "no"
    }
    "Hello World" match {
      case StartsWith('g') | EndsWith('d') => "yes"
      case _ => "no"
    }
    
  3. Die Baumrepräsentation ähnelt der von IntList. Die Extraktoren sollten kein Problem mehr sein.
    
    abstract class IntTree
    
    class Node(val left: IntTree, val right: IntTree) extends IntTree
    object Node {
      def apply(left: IntTree, right: IntTree) = new Node(left, right)
      def unapply(n: Node) = Some(n.left, n.right)
    }
    
    class Leaf(val i: Int) extends IntTree
    object Leaf {
      def apply(i: Int) = new Leaf(i)
      def unapply(l: Leaf) = Some(l.i)
    }
    
    object Empty extends IntTree
    
    val tree: IntTree = Node(Leaf(8), Node(Node(Leaf(9), Empty), Node(Leaf(9), Empty)))
    tree match {
      case Node(Leaf(i @ 8), Node(Node(Leaf(j @ 9), Empty), _)) => "found:"+i+","+j
      case _ => "nothing found"
    }
    

No comments yet

Hinterlasse einen Kommentar