pattern-matching.js
Provides pattern matching features typically found in functional languages like Elixir/Erlang, ML, F#, etc.
Installation
TODO
match
function
The The match function lets us compare a value against many patterns until we find one that matches.
import { match, __ } from "pattern-matching"
match([1, 2, 3],
[ [4, 5, 6], () => "This clause won't match" ],
[ [1, __, 3], () => "This clause will match, __ will match any value" ],
[ __, () => "This clause would match any value" ])
"This clause will match, __ will match any value"
The value that was passed into match
is also passed to the callback:
const x = 10
match(x,
[ __, (value) => value * 10])
100
If none of the cases match and error is thrown:
match([1, 2, 3]
[ [1, 2], () => "this won't match as the array lengths don't agree"])
// (Error) unmatched case: [1, 2, 3]
Array’s are matched as tuples, the lengths have to be the same:
match([1, 2, 3]
[ [1, 2], () => "this won't match"],
[ [1, 2, 3], () => "this will match"])
"this will match"
The tail of a list can be matched with __.rest
, or it’s aliases __.tail
or __.tl
:
import { match, __ } from "pattern-matching"
match(range(50, 100),
[ [50, 51, __.rest], () => "this will match"])
"this will match"
Primitive types can be matched with special operators:
import { match, __ } from "pattern-matching"
const thingy: {
data: {
someNumber: 1,
metadata: {foobar: 'foobar'},
someOtherProp: {},
}
list: [1, 2, 3]
};
match(thingy,
[ { data: { someNumber: __.number,
metadata: __.object },
list: [__, __.rest] }, () => "this will match"])
"this will match"
TODOs
- [ ] Add variable captures
- [ ] Proper type inference right-hand-side of match case
- [ ] Exhaustive type check for match cases