TypeScript icon indicating copy to clipboard operation
TypeScript copied to clipboard

Pattern Matching Support

Open dignifiedquire opened this issue 12 years ago • 64 comments

I've seen some short notions about pattern matching on code plex, but no serious discussions around it. As I'm a big fan of it, I've written up some small examples on how I think pattern matching could look in TypeScript.

This is by far no complete specification, just some ideas that I want to bring forward and have a little discussion around.

Function Overloading

// Pattern matching on functions

function pickCard {
  (x: {suit: string; card: number; }[]): number {

    var pickedCard = Math.floor(Math.random() * x.length);
    return pickedCard;  

  }
  (x: number): {suit: string; card: number; } {

    var pickedSuit = Math.floor(x / 13);
    return { suit: suits[pickedSuit], card: x % 13 };

  }
} 
// Translation of functions.ts using sparkler
// https://github.com/natefaubion/sparkler

function pickCard(x) {
  [...{ suit @ String, card @ number }] =>  {
    var pickedCard = Math.floor(Math.random() * x.length);
    return pickedCard;  
  }
  x @ Number => {
    var pickedSuit = Math.floor(x / 13);
    return { suit: suits[pickedSuit], card: x % 13 };
  }
} 

Match statement

// Pattern matching using match

function whoami (x: any): string {

  match x {
    case { name: string, type: 'person' }: 
        return 'Person: ' + name;

    case { name: string, type: 'animal' }: 
        return 'Animal: ' + name;

    default: 
        return 'Unkown you';
  }
} 
// Pattern matching using match translated

function whoami (x) {

  match x {
    case { name @ String, type: 'person' }: 
        return 'Person: ' + name;

    case { name @ String, type: 'animal' }: 
        return 'Animal: ' + name;

    default: 
        return 'Unkown you';
  }

} 

dignifiedquire avatar Jul 21 '14 19:07 dignifiedquire

I've used a similar pattern. I'm not sure the problem is with subclassing (implementing, really) Shape. After all, they will have to provide an implementation of match, so that is on them.

To me, the bigger issue is when you have lots of mutually exclusive possibilities. It would end up being a bit awkward. But it works and, as I said, I have used this approach.

xogeny avatar Nov 06 '17 13:11 xogeny

Ah...I think I see what you mean by extending Shape. I suppose you are referring to the problem of what to do if they want to add another possibility to the list of possibilities (i.e., growing it from 3 to 4 to ...). In Scala, this is solved by sealing the class (thus freezing the possible subtypes). We don't have that in TypeScript of course.

If you have an open ended set of possibilities, you are probably better of simply defining a perimeter method. If it is a closed set of possibilities (and you don't have the option to "seal" them as in Scala), I think the approach you showed works just fine because the match method effectively closes the set of possibilities for you.

If you really wanted to, I suppose you could do something like this:

interface ShapeHandler<T> {
    square: (x: Square) => T;
    rectangle: (y: Rectangle) => T;
    circle: (z: Circle) => T;
}
interface Shape {
    match<T>(handler: ShapeHandler<T>): T;
}

class Square implements Shape {
    constructor(public size: number) { }
    match<T>(handler: ShapeHandler<T>): T { return handler.square(this); }
}

class Rectangle implements Shape {
    constructor(public width: number, public height: number) { };
    match<T>(handler: ShapeHandler<T>): T { return handler.rectangle(this); }
}

class Circle implements Shape {
    constructor(public radius: number) { };
    match<T>(handler: ShapeHandler<T>): T { return handler.circle(this); }
}

let x: Shape = new Square(10);

console.log(x.match({
    square: (sqr) => { return sqr.size * sqr.size },
    rectangle: (rec) => { return rec.width * rec.height },
    circle: (cir) => { return Math.PI * cir.radius ** 2 }
}));

interface ExtendedShapeHandler<T> extends ShapeHandler<T> {
    triangle: (t: Triangle) => T;
}

class Triangle implements Shape {
    constructor(public a: number, public b: number, public c: number) { };
    match<T>(handler: ExtendedShapeHandler<T>) { return handler.triangle(this) }
}

console.log(x.match({
    square: (sqr) => { return sqr.size * sqr.size },
    rectangle: (rec) => { return rec.width * rec.height },
    circle: (cir) => { return Math.PI * cir.radius ** 2 },
    triangle: (tri: Triangle) => { return tri.a + tri.b + tri.c },
} as ShapeHandler<number>));

I kind of like using named handlers (although it seems as though the type checker would always ensure you didn't have them mixed up). That cast is necessary to keep TypeScript from complaining. But it is still type safe since it is just loosening the semantics around object literals. It still ensures that the value actually has the structure of a ShapeHandler and just seems the triangle bit as "extra" (although the Triangle won't see it that way). But this is still unsafe because we have no way to ensure that an extended shape will get passed an ExtendedShapeHandler.

xogeny avatar Nov 06 '17 13:11 xogeny

That's still quite a lot of boilerplate compared to modern FP languages, plus we don't all use classes :p (I avoid them like the plague)

AlexGalays avatar Nov 06 '17 14:11 AlexGalays

How would you do proper pattern matching in TypeScript if types are erased at runtime? Isn't this pointless

goodmind avatar Nov 06 '17 17:11 goodmind

@goodmind JVM languages such as scala also have to deal with this issue because of type erasure. It's still a very useful tool to have nonetheless and read better than imperative if/else statements.

See https://github.com/tc39/proposal-pattern-matching where everything can be checked at runtime. Although, Things like { x, ... y }: /* match an object with x, stuff any remaining properties in y */ would have to raise compilation errors if the compiler can't know for a fact what the type for y is, when in strict mode.

AlexGalays avatar Nov 06 '17 19:11 AlexGalays

@AlexGalays It's stage 0 tho

goodmind avatar Nov 07 '17 10:11 goodmind

@AlexGalays As far as boilerplate goes, I totally agree. I love pattern matching in Rust, Scala, etc. So thanks for pointing out that proposal. That would be very cool! I'll have to keep an eye on that.

xogeny avatar Nov 07 '17 12:11 xogeny

A discriminated union-based approach may also be an option for you. As per the docs:

type aliases cannot be extended or implemented from (nor can they extend/implement other types)

...which addresses the issue I mentioned earlier re: preventing programmers from adding new implementations of Shape.

Note that exhaustiveness in the switch/case used in the match method is guaranteed by the --strictNullChecks compiler flag plus a return type of T.

interface Square {
    kind: "square";
    size: number;
}

interface Rectangle {
    kind: "rectangle";
    width: number;
    height: number;
}

interface Circle {
    kind: "circle";
    radius: number;
}

type Shape = Square | Rectangle | Circle;

function shape<T>(s: Shape, a: (x: Square) => T, b: (y: Rectangle) => T, c: (z: Circle) => T): T {
    switch (s.kind) {
        case "square": return a(s);
        case "rectangle": return b(s);
        case "circle": return c(s);
    }
}

let x: Square = { "kind": "square", "size": 10 };

console.log(shape(x,
    (sqr) => { return sqr.size * sqr.size },
    (rec) => { return rec.width * rec.height },
    (cir) => { return Math.PI * cir.radius ** 2 }));

laser avatar Nov 07 '17 18:11 laser

@laser You can already do very general discriminator-based pattern matching in JS by doing something like:

const match =  (p, ...c) => {
  const cases = new Map(c)
  return x => cases.get(p(x))(x)
}

const area = match(
  x => x.kind,

  ["square", ({ size }) => size ** 2],
  ["rectangle", ({ width, height }) => width * height],
  ["circle", ({ radius }) => Math.PI * radius ** 2])

console.log(area({ "kind": "square", "size": 10 }))
// => 100

Unfortunately, the typechecker suffers from a kind of death by thousand cuts of missing features here, and while it's almost possible to implement a type definition for match that makes this all work, we're not quite there yet. I've tried to point out the missing features in #19800.

masaeedu avatar Nov 07 '17 18:11 masaeedu

Just saw this issue and thought I'd put in a plug:

https://github.com/pelotom/unionize

You can have pattern matching today!

pelotom avatar Nov 08 '17 17:11 pelotom

@pelotom That looks very cool. I really like the design. I try to use the tagged union approach whenever I can and you seem to have really cleared out the boilerplate for most use cases. I'll definitely check it out!

xogeny avatar Nov 08 '17 22:11 xogeny

One aspect that's important for pattern matching is to not force the requirement of providing an explicit discriminator onto the input data; it should be possible to pattern match on data in its "natural", messy state.

This is important to be able to get all the benefits of pattern matching from other languages (e.g. pattern matching over x:xs in Haskell should map to matching over ([x, ...y]) => in JS. This isn't possible if pattern matching is restricted to a single discriminator property.

E.g. for the shapes thing above, it should be possible to do:

const hasProp = (o, p) => o.hasOwnProperty(p)
const area = match(
  x => hasProp(x, "size") ? "square" : hasProp(x, "radius") ? "circle" : "rectangle",

  ["square",    ({ size })          => Math.pow(size, 2)],
  ["rectangle", ({ width, height }) => width * height],
  ["circle",    ({ radius })        => Math.PI * Math.pow(radius, 2)])

And then be able to match over "raw" data that is not explicitly tagged or prepped for pattern matching:

console.log(
  area({ size: 10 }),
  area({ width: 10, height: 11 }),
  area({ radius: 1 / Math.sqrt(Math.PI) }))
// => 100, 110, 1

This works in JS, so the goal in TypeScript should be to support this with strict type checking and good inference.

masaeedu avatar Nov 08 '17 22:11 masaeedu

Yeah, jumping through hoops just to emulate pattern matching for the one feature that is already very well supported by the compiler (discriminated unions + control flow analysis) is pointless as anything but an exercice. Plus, you lose the free exhaustivity check!

Without compiler support, it's not worth it. Will wait for that TC39 pattern matching proposal to go up in its stages, or for macros :D

AlexGalays avatar Nov 09 '17 08:11 AlexGalays

@AlexGalays

Yeah, jumping through hoops just to emulate pattern matching for the one feature that is already very well supported by the compiler (discriminated unions + control flow analysis) is pointless as anything but an exercice. Plus, you lose the free exhaustivity check!

I’m not sure if you’re referring to Unionize, but it’s not “emulating” pattern matching; it’s using every bit of the existing “very well supported” facility that the compiler provides. And it does exhaustivity checking!

pelotom avatar Nov 09 '17 14:11 pelotom

@pelotom Yes I was referring to it indirectly, along with a few other implementations I've seen.

If you're supporting exhaustivity, I really need to have a look... But you don't have the order-dependent + fall-through characteristic of general purpose pattern matching, right?

AlexGalays avatar Nov 09 '17 14:11 AlexGalays

If you're supporting exhaustivity, I really need to have a look... But you don't have the order-dependent + fall-through characteristic of general purpose pattern matching, right?

Correct, it supports the special case where you are discriminating by a unique tag and providing one case per tag, or a catchall default case to handle the leftovers (in which case you lose exhaustivity checking obv).

pelotom avatar Nov 09 '17 14:11 pelotom

@AlexGalays I want to jump in and comment on something. I never saw @pelotom's unionize as a replacement for full blown pattern matching capability. But there a subset of pattern matching that unionize does an excellent job of representing while eliminating lots of boilerplate. For example, I submitted a PR to the bombadil project and I can imagine that a bunch of the boilerplate there could be cleaned up very nicely with unionize. So I'd argue that while it isn't a replacement for pattern matching support at the language level, I think it is far from "pointless" because it is a huge improvement for some very common cases.

xogeny avatar Nov 09 '17 19:11 xogeny

Take a look at @ahejlsberg's take on this from Microsoft Build 2017. From around 46:42, he uses the never type to ensure that all the possible known shapes have been matched in a regular switch-case statement.

This is a lot like what @tekacs proposed.

LayZeeDK avatar Jan 13 '18 22:01 LayZeeDK

A second plug: Runtypes now supports pattern matching. Here's @masaeedu's shapes example adapted to it:

https://github.com/pelotom/runtypes/blob/a585fc813842ecd852d0ae07a4ff3673018e6c91/examples/src/shapes.ts#L11-L15

pelotom avatar Jan 21 '18 08:01 pelotom

I know this issue has kind of gone stagnant, but I would love to show my support for this feature. Exhaustive pattern matching combined with algebraic data types is my favorite feature of F#. I don't know the specifics of implementing a feature like this in the current code base, but the syntax is so close to being what I want to work with already. I want to write code like this:

type CreditCard = {
    number: number;
    expDate: string;
    cvc: number;
}

type Check = {
    routingNumber: number
    accountNumber: number
}

type PayPal = {
    emailAddress: string
}

type PaymentMethod = CreditCard | Check | PayPal; 

type Payment = {
    Method: PaymentMethod; 
    Amount: number
}

function processPayment(payment: Payment) {
    match (payment) {
        CreditCard: cc => ...//process credit card
        Check: check => ...//process check payment
        // -> Would throw an compile time warning as not all cases have been handled
    }
}

The lightweight types and discriminated union provide a clear, concise, and powerful domain model, and the potential exhaustive pattern matching would round everything out by enforcing that domain model on the developer via the compiler. It's a system that really works very well in the F# world and it would be amazing to see something similar in TS.

It's clearly possible to transpile to javascript that enforces this, as evidenced by the existence of Fable. For now, I'm stuck using Fable basically for this functionality alone. Unfortunately, the developer experience is not as good as TS, and TS retains some of that Javascript flexibility (which I'm a fan of). In my mind, this feature alone would be enough for me to make the switch, and I doubt that I'm the only one.

Thanks for the consideration.

dough654 avatar Feb 15 '19 21:02 dough654