Pattern Matching Support
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';
}
}
We've typically avoided features that require type information at runtime, because many types in TypeScript are indistinguishable from a runtime perspective.
For example, what would the emitted JavaScript look like in this case?
enum Suit { Spades, Hearts, Clubs, Diamonds }
enum Rank { Ace, King, Queen, Jack }
function pickCard {
(s: Suit) : number { return 1; }
(r: Rank): number { return 0; }
}
pickCard(Suit.Spades);
pickCard(undefined);
@RyanCavanaugh You could potentially build in an Ometa-like library that allowed you to do pattern matching of all sorts. You may want a more TS friendly syntax but it would be very compelling. You could do matching on any object not just Types. Here's an example http://www.tinlizzie.org/ometa-js/#Typechecker
"We've typically avoided features that require type information at runtime"
Will that change with the accommodating of the angular2 reflection?
@AlexGalays, i do not think so. one thing we are trying to maintain is keep a single module transpilation possible with no semantic information present.
I have to say, something like this would be insanely nice. What are the chances of this happening?
:+1:
:+1:
:+1:
:+1:
Just wanted to point out a possible alternative that may be available with --noImplicitReturns with the modification mentioned here #5916.
This gets you code that looks like this, and requires no changes to TypeScript whatsoever
interface SomeType {
stringValue: string
}
function isSomeType(x: any): x is SomeType {
return x && typeof(x.stringValue) === 'string';
}
function foo(x: number | string | boolean | SomeType): string {
if(typeof x === 'number' || typeof x === 'boolean') {
return x.toString();
} else if (typeof x === 'string') {
return x;
} else if (isSomeType(x)) {
return x.stringValue;
} else {
return 'other';
}
}
--noImplicitReturns gives us full spectrum matching in a very conventionally JavaScript way. We can now make a pretty trivial helper function match:
function match<T, U>(value: T, matcher: (t: T) => U) {
return matcher(value);
}
And we can use it like this:
const res = match(1, (x: string | boolean | number | SomeType): string => {
if(typeof x === 'number' || typeof x === 'boolean') {
return x.toString();
} else if (typeof x === 'string') {
return x;
} else if (isSomeType(x)) {
return x.stringValue;
} else {
return 'other';
}
});
and
const value: string | boolean | number | SomeType = 5;
const res = match(value, x => {
if(typeof x === 'number' || typeof x === 'boolean') {
return x.toString();
} else if (typeof x === 'string') {
return x;
} else if (isSomeType(x)) {
return x.stringValue;
} else {
return 'other';
}
});
With full safety that we have handled all cases in the union.
New proposal for syntactic sugar
Make match a built-in construct which would look like this:
A language construct that takes an object mapping the type (property name) to a function or literal.
const res = match (value) {
string: s => s,
boolean: b => b.toString,
number: n => n.toString(),
SomeType({ stringValue }) { return stringValue },
default: 'other'
}
All that's happening here is it creates a function for you that creates an if(isType(value)) return typeFn(value) statement, for each function passed in. For primitive types, it uses: typeof (value) === '<primitive>', for "tagged" or disjoint unions specified with type literals, the field containing the literal type could be checked, and for any other type, it checks to see if a function is<Type> exists in scope.
So this maps out to the following code:
const res = ((x: string | boolean | number | SomeType): string => {
if (typeof x === 'string') {
return ((s: string) => s)(x);
} else if (typeof x === 'boolean') {
return ((b: boolean) => b.toString())(x);
} else if(typeof x === 'number') {
return ((n: number) => n.toString())(x);
} else if (isSomeType(x)) {
return (({ stringValue }: SomeType) => stringValue)(x);
} else {
return 'other';
}
})(value);
This somewhat addresses @RyanCavanaugh's concern about enum types or other things which have their type information erased at runtime in the sense that because no isSuit or isRank type guard exists in scope, it would give a compiler error. It could also conceivably give a compiler error in the case of overlapping type literals, since all their values are known at compile time.
As an optimization, if the type being matched on is purely composed of a "tagged"/disjoint union based on type literals, it could output the following:
type Circle = {
shape: 'square'
radius: number
}
type Rectangle = {
shape: 'rectangle'
length: number
width: number
}
type Square = {
shape: 'square'
length: number
}
// because these have a shared literal property
// that will be used as the implicit "tag", and TS
// can know this is a tagged union
type Shape = Circle | Rectangle | Square
const shape: Shape = getShape(); // some shape
function getArea(shape: Shape) {
return match shape {
Circle: ({ radius }) => 3.14 * (radius * radius),
Rectangle: ({ length, width }) => length * width,
Square: ({ length }) => length * length,
};
}
The getArea function would be translated in an optimized way to look like this:
function getArea(shape: Shape) {
return ({
/* Circle.shape literal */ 'circle': ({ radius }) => 3.14 * (radius * radius),
/* Rectangle.shape literal */ 'rectangle': ({ length, width }) => length * width,
/* Square.shape literal */ 'square': ({ length }) => length * length,
})[shape.shape](shape);
}
:thumbsup:
But why not erlang style function guards? The syntax proposed above is a little funky.
function animal(species: Cat) {
species.meow();
}
function animal(species: Dog) {
species.bark();
}
becomes:
function animal(species: Cat | Dog) {
if (species instanceof Cat) {
species.meow();
} else if (species instanceof Dog) {
species.bark();
}
}
or checking values:
function animal(alive: true) : string {
return "Is alive";
}
function animal(alive: false) : string {
return "Is not alive";
}
Personally, I wouldn't call it funky, since it's pretty common (i.e. found a lot of adoption). Here's a incomplete list of languages that come to mind:
There are ought to be plenty more, those just came to the top of my head.
You can check values using guards then, i.e. case x:xs | x == 0 to check if this is a list where the first element is a 0.
Your suggestions reminds me of multi-methods in lisp or function lookup based on arity like in elixir.
@zvxy it sounds more like your asking for a feature to automatically combine function overloads into a single function. It's a nice idea, but it wouldn't work for interfaces unless TypeScript could automatically create an interface type guard, which is impossible in ambiguous cases.
@felixSchl
I couldn't really find a better word for it than "funky", but you're right, this isn't pattern matching and is actually arity overloading. I do code in rust occasionally (and elixir/haskell is love). Here's a quick way I had to do it in rust:
trait Multiply {
fn multiply(self, i32) -> i32;
}
impl Multiply for String {
fn multiply(self, n: i32) -> i32 {
self.parse::<i32>().unwrap() * n
}
}
impl Multiply for i32 {
fn multiply(self, n: i32) -> i32 {
self * n
}
}
fn test<T: Multiply>(x: T, n: i32) -> i32 {
x.multiply(5)
}
fn main() {
println!("{}", test("5".to_owned(), 5)); //25
println!("{}", test(5, 5)); // 25
}
Rust is notoriously verbose. I'd like to just do this:
fn test(x: String, n: i32) -> i32 {
self.parse::<i32>().unwrap() * n
}
fn test(x: i32, n: i32) -> i32 {
x * n
}
But I can't...
@tejacques
You're right, I had forgotten about interfaces (I have been switching between languages). Do you have any alternative solutions?
@zvxy As @tejacques correctly pointed out we are talking about different things. But still, here is what this could look like in rust, using ADTs and matching:
enum Foo {
Foo(String),
Bar(i32),
}
fn test(x: Foo, n: i32) -> i32 {
n * match x {
Foo::Foo(s) => s.parse::<i32>().unwrap(),
Foo::Bar(n) => n,
}
}
#[test]
fn it_works() {
assert_eq!(test(Foo::Foo("5".to_owned()), 5), 25);
assert_eq!(test(Foo::Bar(5), 5), 25);
}
Not that verbose. I see where you are coming from, though. I missed function overloading by type for quite a while when leaving C#, but once I got the hang of ADTs, I don't really see the point anymore.
@felixSchl yeah, I had edited my post right before you responded about it being arity overloading and not pattern matching, my mistake.
You said you don't really see the point anymore, but as far as I'm aware that code is going to be checked during runtime, not compile time. This is going a bit off topic though.
why not extending switch statement, just like C#.
@alrz The answer is in your question - because it's a statement. See how in the rust example above I could multiply the result of the match expression? Statements are inflexible and enforce imperative style coding. Take try/catch, for example, or the for loop, while loop, any loop. Personally, I wish languages would part entirely from these constructs. Let's even take if as an example. Here's some contrieved purescript:
let y = if x == 0 then "foo" else "bar"
which you would need to do imperatively using if statements:
let y: string; // <- I have to tell the compiler the type and cannot at compile time reason about if this value is going to null or not :(
if (x == 0) {
y = "foo";
} else {
y = "bar";
}
To be fair, there are ternary expressions in js/ts:
const y = (x == 0) ? "foo" : "bar";
@zvxy I think the only thing you can do for interfaces (at least that I can think of) is check the scope for a function that guards on that interface, but this is far from perfect.
:+1: