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';
}
}
You could do redundant pattern matching right now
class Some {
constructor(public val: string) {
}
}
class None {
}
type Maybe = Some | None;
var a = new Some("val");
if (a instanceof Some) {
console.log(a.val);
}
But some syntax sugar would be appreciated.
Any reason https://github.com/bendetat/SimplicityJS wouldn't work with TS?
Pattern matching is one of the most useful features of "more powerful" languages like Swift, Scala and Rust. I'd highly welcome this feature as part of Typescript!
@tejacques Do you have an update of your interesting example for typescript 2.0 ?
This is definitely a feature that would make me switch to TypeScript for every project.
Whenever you're dealing with a CQRS architecture, pattern matching has to come along the way.
That'd allow people to create a strongly typed Flux / Redux implementation. For now, only Elm offers such possibility.
Strongly-typed actions + type aliases + ADT + pattern matching are a bless when dealing with such architecture. You're basically covered that if the code compiles, it's gonna work pretty much without runtime exceptions.
If you declare a reducer for a certain type of action. Your whole chain is now strongly typed.
In current implementations :
function updateState(action, state) {
switch(action.type) { // a String...
case 'create':
var newTodo = action.data; // is data really an object ? shouldn't the compiler know ?
state[newTodo.id] = newTodo; // and if state is not purely a map ? what if todo as no 'id' ?
}
}
With type algebra + pattern matching this would become (sorry for pseudo-code) :
type alias Todo = {id: String, items: Array[String]}
val CreateTodo = Action(Todo)
val RemoveTodo = Action({id: String})
type alias TodoAction = CreateTodo | RemoveTodo
type alias SomeState = Map[Todo]
function updateState(action: TodoAction, state: SomeState) {
match action.type {
case CreateTodo newTodo => // here the compiler knows that newTodo is {id: String, items: Array[String]})
case UpdateTodo {id} => state.remove(id)
// => no default, the compiler wouldn't compile if I forgot about some case
}
}
Typescript seems to already offer the strongly-typed system, the destructuring ability. The only thing this example misses would be pattern matching to be a little more readable, and more safety, and let the compiler check for most of the errors that today occur in production (example : payload.action doesn't have the right type)
@aesteve In today's TypeScript 2.0 code, your 'pseudocode' can be written as follows and works fine:
Preamble:
interface Todo {
id: string
items: string[]
}
interface CreateTodo {
kind: 'create'
todo: Todo
}
interface RemoveTodo {
kind: 'remove'
id: string
}
type TodoAction = CreateTodo | RemoveTodo;
type SomeState = Map<string, Todo>;
function updateState(action: TodoAction, state: SomeState) {
switch (action.kind) {
case 'create': // here the compiler knows that action is CreateTodo, of {id: String, items: string[]}
case 'remove': state.delete(action.id)
default: const _exhaustiveCheck: never = action
}
}
The argument about automatic exhaustivity checking for the above seems to have been had in #9260 (see the last few comments including my own for a summary).
I've started to propose (but haven't had time yet to formalise) doing this with overloading in #10765, so that it would look like this (for the times that it's more convenient to write these separately):
function updateState(action: CreateTodo, state: SomeState) {
// here the compiler knows that the action is CreateTodo
}
function updateState(action: DeleteTodo, state: SomeState) {
state.delete(action.id)
}
function updateState(action: TodoAction, state: SomeState): never {} // unclear if there's a better syntax for doing this bit
Much of what is being asked for in pattern matching is already possible in TS 2.0.0 (Thanks!). It is achieved without storing any runtime type information too. But for me, the one thing that would be nice would be more intuitive syntax. For example, right now I can write code like this.
class Foo {
public name: string;
}
class Bar {
public title: string;
}
type Stringable = A | B;
function stringOf(a: Stringable): string {
if (a instanceof Foo) return a.name;
return a.title;
}
That's great. But something like this would just be easier to read:
function stringOf(a: Stringable): string {
a match {
case Foo: return a.name;
case Bar: return a.title;
}
}
My point here is that using this strictly with classes could avoid some of the "having to include runtime information" because you could piggy back off of what is already included (i.e., the same information that instanceof is using). Of course, instrumenting this with destructuring and guards would be really cool too! e.g.,
function lengthOf(a: Stringable): number {
a match {
case Foo({ name }) if name: return name.length;
case Bar({ title }) if title: return title.length;
default: return 0;
}
}
My guess is that what's already been implemented with type narrowing could be completely reused here. As far as I can tell, this is just syntactic sugar for:
function lengthOf(a: Stringable): number {
if (a instanceof Foo && a.name) return a.name.length;
else if (a instanceof Bar && b.title) return a.title.length;
else return 0;
}
...with the same possibilities for detection mutual exhaustion.
Or am I missing something?
I put together a quick example using current TypeScript 2.0 syntax, where the pattern matching function looks like this:
function testMatch(a: any): number {
return match(a,
Case(Foo, f => f.n),
Case(Bar, b => b.foo.n),
Case(23, n => n + 1),
Case('asdf', s => s.length),
Case(a + 1 === 2, () => 2),
DefaultCase(-1)
);
}
The match/Case syntax looks kinda similar to some of the above suggestions if you dim the lights and squint a bit. I'm not suggesting using it in production, but it was fun hacking it together until the real thing comes along ;-)
Here's the full example as a TypeScript 2.0 Playground example with the following code:
interface Type<T> { new(...args): T }
interface CaseResult<R> {
success: boolean;
result: R;
}
interface CaseFn<R> { (value: any): CaseResult<R> }
function Case<R>(t: number, p: (n: number) => R): CaseFn<R>;
function Case<R>(t: string, p: (s: string) => R): CaseFn<R>;
function Case<T, R>(t: Type<T>, p: (t: T) => R): CaseFn<R>;
function Case<R>(t: boolean, p: () => R): CaseFn<R>;
function Case<R>(type: any, project: (t: any) => R): CaseFn<R> {
return (a) => {
const success = !!a && (
typeof type === 'function' && a instanceof type ||
typeof type === 'boolean' && type ||
typeof type === typeof a && type === a
);
const result = success && project(a);
return { success, result };
}
}
function DefaultCase<R>(value: R): CaseFn<R> {
return (_) => ({ success: true, result: value });
}
function match<A, R>(a: A, ...cases: CaseFn<R>[]): R {
for (var i = 0; i < cases.length; i++) {
const r = cases[i](a);
if (r.success) {
return r.result;
}
}
return undefined;
}
class Foo { constructor(public s: string, public n: number) { } }
class Bar { constructor(public n: number, public foo: Foo) { } }
class Baz { constructor(public s: string, public bar: Bar) { } }
function testMatch(a: any): number {
return match(a,
Case(Foo, f => f.n),
Case(Bar, b => b.foo.n),
Case(23, n => n + 1),
Case('asdf', s => s.length),
Case(a + 1 === 2, () => 2),
DefaultCase(-1)
);
}
let foo = new Foo('foo', 1);
let bar = new Bar(2, foo);
let baz = new Baz('baz', bar);
alert('foo: ' + testMatch(foo)); // 1
alert('bar: ' + testMatch(bar)); // 2
alert('baz: ' + testMatch(baz)); // -1
alert('23: ' + testMatch(23)); // 24
alert('asdf: ' + testMatch('asdf')); // 4
alert('a + 1: ' + testMatch(1)); // 2
UPDATE: added simple boolean predicate case.
I published your library at https://github.com/jroitgrund/pattern-matcher so people can pull it in and contribute, hope you don't mind @rob3c, if so let me know and I will take it down.
One caveat: this doesn't work for interfaces, because they don't have a constructor generated so you can't do "typeof".
@jroitgrund You're welcome to publish that proof-of-concept code for anyone that finds it useful. Calling it a library seems a bit generous, but I'll take it ;-)
Of course, I'm hoping a more official baked-in solution comes along, but maybe this is all we'll have for a while.
@jroitgrund Oh, and while interfaces aren't directly supported because they don't really exist at runtime, it is possible to leverage interface type guards with an additional Case signature, like this:
// ...
function Case<T, R>(t: Type<T>, p: (t: T) => R): CaseFn<R>;
function Case<T, R>(test: (x: any) => x is T, p: (t: T) => R): CaseFn<R>; // <--- NEW
function Case<T, R>(t: boolean, p: () => R): CaseFn<R>;
// ...
and then this will work:
// ...
interface Qux { q: number; }
function isQux(obj: any): obj is Qux {
return obj && 'q' in obj && typeof obj.q === 'number';
}
function testMatch(a: any): number {
return match(a,
// ...
Case(isQux, qux => qux.q),
DefaultCase(-1)
);
}
// ...
const qux: Qux = { q: 123 };
const quacksLikeAQux = { q: 456 };
const notAQux = { q: 'nope' };
// ...
alert('qux: ' + testMatch(qux)); // 123
alert('quacksLikeAQux: ' + testMatch(quacksLikeAQux)); // 456
alert('notAQux: ' + testMatch(notAQux)); // default
UPDATE: This was thrown together too hastily and didn't account for the challenge of distinguishing constructor functions from type guards/predicates. That's more easily accomplished in a separate FnCase that's specific to predicates. Fortunately, @Aleksion caught it quickly, and added support for it as well as sync functions in this pattern-matcher PR for anyone who's interested.
@rob3c 's trick is good but I hope it doesn't serve as a reason NOT to implement pattern matching natively. Creating an anonymous function for every case is not performant, the syntax also is far from clean compared to a native implementation.
It's very rare to pattern match against very heterogenous types, so with ADTs I will stay with:
function getView(model: SomeADT) {
if (model.type === 'type1') return View1(model)
if (model.type === 'type2') return View2(model)
else return View3()
}
Not very elegant, and requires a function scope (JS and everything is a statement :( ) but still largely readable.
Then again, since TS doesn't want to include anything not already found in JS, implementing macros instead could save the day? :p
How about exactly like c# 7.1
if(v is int i)
{
add(i,1);
}
switch(shape)
{
case Circle c:
WriteLine($"circle with radius {c.Radius}");
break;
case Rectangle s when (s.Length == s.Height):
WriteLine($"{s.Length} x {s.Height} square");
break;
case Rectangle r:
WriteLine($"{r.Length} x {r.Height} rectangle");
break;
default:
WriteLine("<unknown shape>");
break;
case null:
throw new ArgumentNullException(nameof(shape));
}
As documented here:https://blogs.msdn.microsoft.com/dotnet/2017/03/09/new-features-in-c-7-0/
@jvelezc Scala has a much nicer syntax:
def goIdle(device: Device) = device match {
case p: Phone => p.screenOff
case c: Computer => c.screenSaverOn
}
val y = x match {
case Pair(i, s) => Pair(s + i, i * i)
}
(x, y) => (x, y) match {
case (a, (b, c)) => a + b * c
}
But yeah, the thing with pattern matching is that it differs from ECMAScript standards and proposed standards. So we'll have to be like other exceptions in TypeScript such as interface if we want proper pattern matching support built-in.
It'd be lovely if we could make Scala's pattern matching syntax more widely accepted this way. I am certainly a fan of moving it in that direction. The only big change is that we'd be diverging not only from ES but also the Typescript idea that removing all annotations would produce the same runtime behavior on valid code. Being that we already have to have a compile phase with TS, I don't see a problem with it producing more useful code.
While reflecting on runtime types may not fit well with the zen of TypeScript, matching on Haskell style labeled unions should be possible. I was trying to get this to work correctly, but there's some issues with inference on unions (#2264) that makes it annoying to use:
type Case<T extends string> = { _: T }
type Maybe<T> = { _: "just", value: T } | { _: "none" }
function match<
C1 extends string, U1 extends Case<C1>,
C2 extends string, U2 extends Case<C2>>(
data: U1 | U2,
c1: C1, p1: (data: U1) => any,
c2: C2, p2: (data: U2) => any): any
/* more overloads... */
function match(...args: any[]): any
{ /* ... */ }
// Almost, but x is inferred as just Case<"just"> instead of { _: "just", value: T } :(
match(
<Maybe<number>>undefined,
"just", x => console.log(x),
"none", () => console.log('nope'))
// Whoops, this is a type error
match(
<Maybe<number>>undefined,
"wrong", x => console.log('nope'),
"just", x => console.log('foo'))
FYI. tc39 recently released a stage 0 proposal to add pattern matching as an official javascript feature https://github.com/tc39/proposal-pattern-matching
Recently published a tiny library: https://www.npmjs.com/package/typematcher
import {match, caseId, caseThrow, isEither, isString, isValue, isNumber, isOptional} from 'typematcher'
enum Gender {
Male = 'M',
Female = 'F'
}
type User = {
name: string,
gender: Gender,
age: number
address?: string
}
const user: User = match({})(
caseId(
hasFields({
name: isString,
gender: isEither(isValue(Gender.Male), isValue(Gender.Female)),
age: isNumber,
address: isOptional(isString)
})
),
caseWhen(isNumber)(n => {
throw new Error("Number not an user");
}),
caseThrow(new Error("Invalid user object"))
);
Sources: https://github.com/lostintime/node-typematcher Short intro: https://lostintimedev.com/2017/09/06/typematcher-pattern-matching-library-for-typescript.html
+1 for native scala-like syntax
Here's another implementation of pattern matching for sum types using dynamic dispatch:
// Just for readability
type Sum<Components> = Components
// Keys are the names/indices of the components, values are the types of the components
type SomeSumType = Sum<{
NUMBER: number
STRING: string
}>
// ST is for SumType
interface CaseOf<ST> {
match: <T>(pattern: Pattern<ST, T>) => T
}
// T is for TargetType
type Pattern<ST, T> = {
[key in keyof ST]: (cas: ST[key]) => T
}
const createCase = <ST, K extends keyof ST>(k: K, value: ST[K]): CaseOf<ST> => ({
match: <T>(pattern: Pattern<ST, T>) => pattern[k](value)
})
const a: CaseOf<SomeSumType> = createCase('NUMBER', 5)
const b: CaseOf<SomeSumType> = createCase('STRING', 'someString')
const notA: CaseOf<SomeSumType> = createCase('NUMBER', 'wrongType') // Type error
const wrongCase: CaseOf<SomeSumType> = createCase('C', 'test') // Type error
const match = <CS, T>(cas: CaseOf<CS>, pattern: Pattern<CS, T>) => cas.match(pattern)
const result = match<SomeSumType, boolean>(a, {
NUMBER: num => num > 6,
STRING: str => str === 'expectedString'
})
Achieving a similar effect with Church encoding, as per Rúnar Bjarnason:
interface Shape {
match<T>(a: (x: Square) => T, b: (y: Rectangle) => T, c: (z: Circle) => T): T;
}
class Square implements Shape {
constructor(public size: number) { }
match<T>(a, b, c): T { return a(this); }
}
class Rectangle implements Shape {
constructor(public width: number, public height: number) { };
match<T>(a, b, c): T { return b(this); }
}
class Circle implements Shape {
constructor(public radius: number) { };
match<T>(a, b, c): T { return c(this); }
}
let x: Shape = new Square(10);
console.log(x.match(
(sqr) => { return sqr.size * sqr.size },
(rec) => { return rec.width * rec.height },
(cir) => { return Math.PI * cir.radius ** 2 }));
The major problem with this approach (in TypeScript) is that I see no way to prevent library consumers from subclassing Shape.