Last active
February 12, 2019 13:01
-
-
Save raganwald/61f35dc4d88d25eefc954da8cfa90c01 to your computer and use it in GitHub Desktop.
Recursive Pattern Matching using the Why Combinator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const just = | |
target => | |
input => | |
input.startsWith(target) && | |
target; | |
const cases = | |
(...patterns) => | |
input => { | |
const matches = patterns.map(p => p(input)).filter(m => m !== false); | |
if (matches.length === 0) { | |
return false; | |
} else { | |
return matches.sort((a, b) => a.length > b.length ? -1 : +1)[0] | |
} | |
}; | |
const follows = | |
(...patterns) => | |
input => { | |
let matchLength = 0; | |
let remaining = input; | |
for (const pattern of patterns) { | |
const matched = pattern(remaining); | |
if (matched === false) return false; | |
matchLength = matchLength + matched.length; | |
remaining = input.slice(matchLength); | |
} | |
return input.slice(0, matchLength); | |
}; | |
const zeroOrMore = | |
pattern => | |
input => { | |
let matchedLength = 0; | |
let remaining = input; | |
while (remaining.length > 0) { | |
const matched = pattern(remaining); | |
if (matched === false || matched.length === 0) break; | |
matchedLength = matchedLength + matched.length; | |
remaining = remaining.slice(matched.length); | |
} | |
return input.slice(0, matchedLength); | |
}; | |
const oneOrMore = | |
pattern => | |
input => { | |
let matchedLength = 0; | |
let remaining = input; | |
while (remaining.length > 0) { | |
const matched = pattern(remaining); | |
if (matched === false || matched.length === 0) break; | |
matchedLength = matchedLength + matched.length; | |
remaining = remaining.slice(matched.length); | |
} | |
return matchedLength > 0 && input.slice(0, matchedLength); | |
}; | |
const entirely = | |
pattern => | |
input => { | |
const matched = pattern(input); | |
return matched !== false && | |
matched === input && | |
matched; | |
}; | |
const why = | |
fn => | |
( | |
maker => | |
(...args) => | |
fn(maker(maker), ...args) | |
)( | |
maker => | |
(...args) => | |
fn(maker(maker), ...args) | |
); | |
entirely( | |
why( | |
(balanced, input) => | |
zeroOrMore( | |
cases( | |
follows(just('('), balanced, just(')')), | |
follows(just('['), balanced, just(']')), | |
follows(just('{'), balanced, just('}')) | |
) | |
)(input) | |
) | |
)('((())())'); | |
//=> '((())())' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment