-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUtils.java
More file actions
95 lines (79 loc) · 2.72 KB
/
Copy pathUtils.java
File metadata and controls
95 lines (79 loc) · 2.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package com.company;
import java.util.List;
import java.util.function.Function;
import static com.company.Tuple.*;
import static com.company.Parser.*;
import static com.company.ParseResults.*;
public class Utils {
public static Parser<Character> item(){
return new Parser<Character>(s ->{
if (s.canAdvance()){
Character c = s.head();
Text rest = s.advance();
return result(t(c,rest));
} else {
return ParseResults.empty();
}
});
}
public static Parser<Character> satisfy(Function<Character,Boolean> predicate){
return new Parser<Character>(s -> {
ParseResults<Character> r = parse(item()).apply(s);
if (r.size() > 0){
Tuple<Character,Text> t = r.get(0);
if (predicate.apply(t.getA())){
return r;
} else {
return ParseResults.empty();
}
} else {
return ParseResults.empty();
}
});
}
public static Parser<Character> chr(Character chr){
return satisfy(c-> c==chr);
}
public static Parser<Character> oneOf(List<Character> list){
return satisfy(list::contains);
}
public static Parser<Character> noneOf(List<Character> list){
return satisfy(c-> !list.contains(c));
}
public static Parser<String> str(String str){
if (str.length() == 0){
return pure(str);
}
return chr(str.charAt(0)) .bind(c ->
str(str.substring(1)) .bind(cs ->
pure(c + cs)));
}
public static Parser<String> _str(String str){
return str_fast(str).bind(cs -> pure(cs.reverse().toString()));
}
private static Parser<StringBuilder> str_fast(String str){
if (str.length() == 0){
return pure(new StringBuilder());
}
return chr(str.charAt(0)) .bind(c ->
str_fast(str.substring(1)) .bind(cs ->
pure(cs.append(c))));
}
public static <A> Parser<FList<A>> many(Parser<A> p){
return many1(p).alt(pure(new Empty<A>()));
}
public static <A> Parser many1(Parser<A> p){
return p .bind(x ->
many(p) .bind(xs ->
pure(new Cons(x,xs)) ));
}
public static <A> Either<ParseError,ParseResults<A>> test(Text s, Parser<A> p){
ParseResults<A> results = parse(p).apply(s);
if (results.size() > 0){
return new Right(results);
} else{
ParseError err = new ParseError(null);
return new Left(err);
}
}
}