Skip to content

Pattern Matching Support #165

Closed
Closed
@dignifiedquire

Description

@dignifiedquire

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';
  }

} 

Metadata

Metadata

Assignees

No one assigned

    Labels

    Out of ScopeThis idea sits outside of the TypeScript language design constraintsSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions