Using the combinator pattern
A combinator is a function that takes other functions as arguments and returns a new function.
A simple example of a combinator would be the composition operator, which chains two functions together:
fn compose<A,B,C,F,G>(f: F, g: G) -> impl Fn(A) -> C where F: 'static + Fn(A) -> B, G: 'static + Fn(B) -> C { move |x| g(f(x)) } fn main() { let fa = |x| x+1; let fb = |y| y*2; let fc = |z| z/3; let g = compose(compose(fa,fb),fc); println!("g(1) = {}", g(1)); println!("g(12) = {}", g(12)); println!("g(123) = {}", g(123)); }
Parser combinators
Another major application of combinators is parser combinators. A parser combinator makes use of both the monad and combinator patterns. The monadic bind
functions are used to bind data from parsers that are later returned as a parse result. The combinators join parsers into a sequence, failover, or other patterns.
The chomp
parser combinator library is a good implementation...