Skip to content
Browse files

Added chainl1 parser combinator.

Chainl1 lifted from Haskell parsec for left-recursive application of binary infix operators

I translated this to non ParserM syntax, and tested works still in nape-symbolic.
  • Loading branch information...
1 parent 8c487ba commit 20da4829079c68dd1c238d00c46a613e82a1fa74 @deltaluca deltaluca committed
Showing with 23 additions and 0 deletions.
  1. +23 −0 src/com/mindrocks/text/Parser.hx
View
23 src/com/mindrocks/text/Parser.hx
@@ -551,6 +551,29 @@ typedef Head = {
or(rep1sep(p1, sep), success([]))
/*
+ * Produce left recursive application of possible infix binary operators to p1 parsers.
+ *
+ * eg:
+ * chainl1(numberParser, divSymbolParser.then((function (x:Float, y:Float) return x / y).success()));
+ * which operating on 1 / 2 / 3
+ * would parse and evaluate the result of (1 / 2) / 3
+ *
+ * p1 parser must be matched at least once.
+ */
+ public static function chainl1 < I,T > (p1 : Void -> Parser<I,T>, op : Void -> Parser<I,T->T->T> ) : Void -> Parser < I, T >
+ {
+ function rest (x : T) return
+ op.andThen(function (f : T->T->T) return
+ p1.andThen(function (y : T) return
+ rest(f(x, y))
+ )
+ ).or(x.success());
+
+ return p1.andThen(rest);
+ }
+
+
+ /*
* 0..1
*/
public static function option < I,T > (p1 : Void -> Parser<I,T>) : Void -> Parser < I,Option<T> > return

0 comments on commit 20da482

Please sign in to comment.
Something went wrong with that request. Please try again.