From 859b3715c8c2e9e3debe637bb15b791d75e49153 Mon Sep 17 00:00:00 2001 From: Kota Mizushima Date: Fri, 9 Dec 2016 18:29:27 +0900 Subject: [PATCH] Add explanation --- README.md | 66 ++++++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 63 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 8dcfd36..42db05c 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ to reduce boilerplate code using lambda expression. To use jcombinator, Add the following lines to your pom.xml -``` +```xml com.github.kmizu @@ -20,6 +20,66 @@ To use jcombinator, Add the following lines to your pom.xml ``` -## Usage +### Usage + +See [JavaDoc](http://javadoc-badge.appsp ot.com/com.github.kmizu/jcombinator/index.html#com.github.kmizu.jcombinator.package) and [Tests](https://github.com/kmizu/jcombinator/tree/releases%2F0.0.1/src/test/java/com/github/kmizu/jcombinator) + +### Example + +The following code is a parser of arithmetic expression: + +```java + +import com.github.kmizu.jcombinator.datatype.Function2; + +import static com.github.kmizu.jcombinator.Parser.*; +import static com.github.kmizu.jcombinator.Functions.*; + +public class ArithmeticExpression { + private Rule expression() { + return rule(() -> + additive().cat(eof()).map(t -> t.extract((result, __) -> result)) + ); + } + private Rule additive() { + return rule(() -> { + final Parser> Q = string("+").map(op -> (Integer lhs, Integer rhs) -> lhs + rhs); + final Parser> R = string("-").map(op -> (Integer lhs, Integer rhs) -> lhs - rhs); + return multitive().chain(Q.or(R)); + }); + } + private Rule multitive() { + return rule(() -> { + final Parser> Q = string("*").map(op -> (Integer lhs, Integer rhs) -> lhs * rhs); + final Parser> R = string("/").map(op -> (Integer lhs, Integer rhs) -> lhs / rhs); + return primary().chain(Q.or(R)); + }); + } + private final Rule primary() { + return rule(() -> + number().or((string("(").cat(expression())).cat(string(")")).map(t -> t.item1().item2())) + ); + } + private final Rule number() { + return rule(() -> + digit().many1().map(digits -> Integer.parseInt(join(digits, ""))) + ); + } -See [JavaDoc](http://javadoc-badge.appspot.com/com.github.kmizu/jcombinator.svg?label=javadoc)](http://javadoc-badge.appsp ot.com/com.github.kmizu/jcombinator/index.html#com.github.kmizu.jcombinator.package) and [Tests](https://github.com/kmizu/jcombinator/tree/releases%2F0.0.1/src/test/java/com/github/kmizu/jcombinator) + public void testExpression() { + Parser arithmetic = expression(); + arithmetic.invoke("100").onSuccess(s -> { + assert ((Integer)100) == s.value(); + }); + arithmetic.invoke("100+200").onSuccess(s -> { + assert ((Integer)300) == s.value(); + }); + arithmetic.invoke("(1+2)*(3+4)").onSuccess(s -> { + assert ((Integer)21) == s.value(); + }); + arithmetic.invoke("1+2*3+4").onSuccess(s -> { + assert ((Integer)11) == s.value(); + }); + } +} +``` \ No newline at end of file