Skip to content

Instantly share code, notes, and snippets.

@kmizu
Last active July 27, 2017 16:50
Show Gist options
  • Save kmizu/a8a07a394528875983a18266bac2bf6e to your computer and use it in GitHub Desktop.
Save kmizu/a8a07a394528875983a18266bac2bf6e to your computer and use it in GitHub Desktop.
Javaで始めるパーザコンビネータの作り方(5)~補足 ref: http://qiita.com/kmizu/items/d3d0f9511f631635d4b2
package parser;
public class Main {
public static void main(String[] args) {
Parser<List<String>> hellos = Parser.string("Hello").many();
System.out.println(hellos.invoke("Hello, World!"));
}
}
Success([Hello], , World!)
package parser;
public class EOFParser implements Parser<String> {
@Override
public ParseResult<String> invoke(String input) {
if(input.length() != 0) {
return new ParseResult.Failure<>("expected: EOF, actual: " + input.charAt(0), input);
} else {
return new ParseResult.Success<String>("", "");
}
}
}
package parser;
public interface Parser<T> {
ParseResult<T> invoke(String input);
static Parser<String> string(String literal) {
return new StringParser(literal);
}
default Parser<T> or(Parser<T> rhs) {
return new Or<>(this, rhs);
}
default <U> Parser<Tuple2<T, U>> cat(Parser<U> rhs) {
return new Cat<>(this, rhs);
}
default Parser<List<T>> many() {
return new ManyParser<T>(this);
}
static Parser<String> EOF() {
return new EOFParser();
}
}
public class Main {
public static void main(String[] args) {
Parser<Tuple2<List<String>, String>> hellos = Parser.string("Hello").many().cat(Parser.EOF());
System.out.println(hellos.invoke("Hello"));
System.out.println(hellos.invoke("Hello, World!"));
}
}
Success(Tuple2{item1=[Hello], item2=}, )
Failure(expected: EOF, actual: ,, , World!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment