Skip to content

Instantly share code, notes, and snippets.

@WimJongeneel
Last active December 15, 2019 11:42
Show Gist options
  • Save WimJongeneel/7cf7887680da8b4935f979aaec7143bb to your computer and use it in GitHub Desktop.
Save WimJongeneel/7cf7887680da8b4935f979aaec7143bb to your computer and use it in GitHub Desktop.
export const match = <a, b>(value: a) => builder<a, b>(value)(() => undefined, [])
const builder = <a, b>(
value: a
) => (
otherwise: () => b = () => null,
patterns: Array<[Pattern<a>, Fun<a, b>]> = []
) => ({
with: (pattern: a, expr: fun<a, b>) =>
builder(value)(otherwise, [...patterns, [pattern, expr]]),
otherwise: (otherwise: () => b) => builder(value)(otherwise, patterns)
run: (): b => {
const p = patterns.find(p => match_pattern(value, p[0]))
if (p == undefined) return otherwise()
return p[1](value)
}
})
const match_pattern = <a>(value: a, pattern: a) => a === a
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment