curimit / SugarCpp

SugarCpp is a language which can compile to C++11.
135 stars 13 forks source link

Introducing pattern matching for case class #12

Open curimit opened 11 years ago

curimit commented 11 years ago

Pattern matching can match type and value. Here is what it look like.

case class Expr
case class Number<T>(value:T): Expr
case class ExprBin(op:string, l:Expr, r:Expr): Expr

double eval(expr: Expr*) = match expr
                         | ExprBin*("+", l, r) => eval(l) + eval(r)
                         | ExprBin*("-", l, r) => eval(l) - eval(r)
                         | ExprBin*("*", l, r) => eval(l) * eval(r)
                         | ExprBin*("/", l, r) => eval(l) / eval(r)
                         | Number<int>*(v)     => v
                         | Number<double>*(v)  => v
dobkeratops commented 9 years ago

very similar to Rust, this would be awesome; may I suggest simplifying the syntax just a little inline with Rust: lose the mandatory '|' and use the newline/indent to separate cases, and repurpose the '|' for different 'patterns' on the same line e.g. match x { A|B|C=> expr1, C|D=> expr2, ...}. Rust also postfixes an optional 'if' guard which is nice

curimit commented 9 years ago

Thank you very much for your suggestion. This syntax I borrowed from ocaml, however, this haven't been finalized. Your suggestion looks good, maybe I can the | become optional.

ozra commented 9 years ago

Yeah, LiveScript does it too - a must have feature :-)

dobkeratops commented 9 years ago

I've implemented this in my language now. tuple destructuring & rust-like enum-variant patterns. rust does some interesting destructuring with slices too, i haven't copied that yet i'll implement the suggestions for ranges too eg lo..<hi lo<..hi etc