Pattern matching in D

retard re at tard.com.invalid
Sun Mar 7 16:25:01 PST 2010


Sun, 07 Mar 2010 15:38:07 -0800, Walter Bright wrote:

> retard wrote:
>> Sun, 07 Mar 2010 11:17:46 -0800, Walter Bright wrote:
>> 
>>> retard wrote:
>>>> - Pattern matching (extension to enum/string/integer accepting
>>>> switch)
>>> Andrei and Sean have shown how to do that nicely with existing
>>> language features.
>> 
>> Really? I'd really like to see how this is done.
> 
> 
> foo(  v,
>       (int i) { writeln("I saw an int ", i); }, (string s) { writeln("I
>       saw a string ", s); ), (Variant any) { writeln("I saw the default
>       case ", any); }
>     );
> 
> 
> foo is a variadic template which takes its first argument, v, and
> attempts to match it with each delegate in turn. The first one that
> matches is executed.

Ok, that's pretty good.

Now let's see how the pattern matching in Scala works:

val a = 42

val b = 123

// basic matching of values
a match {
  case 1 => println("You gave 1")
  case 2 => // functionality for 2
  case _ => println("The default case")
}

// matching & refs to symbols
a match {
  case `b` => println("You gave 123-1=122")
  case b => println("You gave " + b)
}

trait Spiny
class Animal
class Rabbit extends Animal
class Hedgehog extends Animal with Spiny
class Bear extends Animal
object Roger extends Rabbit
object Yogi extends Bear

// matching & subtyping
def foo(a:Animal) = a match {
  case Roger => "guess who framed you?"
  case Yogi => "o hai"
  case h: Animal with Spiny => "Possibly a hedgehog"
  case _ => "Giving up"
}

// nested matches
{ case a :: b :: c => 1 }: (List[Int] => Int)

class Expr
case class Value[T](v: T) extends Expr
case class SumExpr(l: Expr, r: Expr) extends Expr
case class MulExpr(l: Expr, r: Expr) extends Expr
case class NegExpr(e: Expr) extends Expr

def foo(e:Expr) = e match {
  case MulExpr(SumExpr(NegExpr(Value(1)), NegExpr(Value(5))), Value(2)) 
=> println("Imagine, this could be used for AST processing")
  case _ => // do nothing
}

{ case <html><a>some link</a></html> => println("found a link inside the 
DOM") }: (scala.xml.Elem => Unit)

I left out some of the more complex functionality, e.g. extractors and 
more complex higher kinded stuff..

> 
> The matching is all done at compile time, of course, and the delegate
> can be inlined.

I guess this tells a lot. No feature is added to D unless it can do 
something statically with zero runtime cost.



More information about the Digitalmars-d mailing list