net.pelsmaeker.katerm.TermMatcher.kt Maven / Gradle / Ivy
The newest version!
package net.pelsmaeker.katerm
/**
* Matches terms.
*/
fun interface Matcher {
/**
* Applies the matcher to the specified term
*
* @return the result of the match, or `null` if the term does not match
*/
fun match(term: I): O?
fun map(f: (O) -> R): Matcher = Matcher { t -> match(t)?.let(f) }
fun filter(f: (O) -> Boolean): Matcher = Matcher { t -> match(t)?.takeIf { f(it) } }
}
//fun Matcher.map(f: (O) -> R): Matcher = Matcher { t -> match(t)?.let(f) }
//fun Matcher.filter(f: (O) -> Boolean): Matcher = Matcher { t -> match(t)?.takeIf { f(it) } }
object M {
fun id(): Matcher = Matcher { t -> t }
fun fail(): Matcher = Matcher { null }
fun term(): Matcher = id()
fun term(m: Matcher, f: (I, O) -> R): Matcher = Matcher { t -> m.match(t)?.let { f(t, it) } }
}