blob: e0064f12e54153b23f714a93466194e5335ab051 (
plain) (
blame)
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
|
package scala.util.parsing;
abstract class Parsers {
type inputType;
trait Parser[a] {
type Result = Option[Pair[a, inputType]];
def apply(in: inputType): Result;
def filter(pred: a => boolean) = new Parser[a] {
def apply(in: inputType): Result = Parser.this.apply(in) match {
case None => None
case Some(Pair(x, in1)) => if (pred(x)) Some(Pair(x, in1)) else None
}
}
def map[b](f: a => b) = new Parser[b] {
def apply(in: inputType): Result = Parser.this.apply(in) match {
case None => None
case Some(Pair(x, in1)) => Some(Pair(f(x), in1))
}
}
def flatMap[b](f: a => Parser[b]) = new Parser[b] {
def apply(in: inputType): Result = Parser.this.apply(in) match {
case None => None
case Some(Pair(x, in1)) => f(x).apply(in1)
}
}
def ||| (p: => Parser[a]) = new Parser[a] {
def apply(in: inputType): Result = Parser.this.apply(in) match {
case None => p(in)
case s => s
}
}
def &&& [b](p: => Parser[b]): Parser[b] =
for (val _ <- this; val x <- p) yield x;
}
def not[a](p: Parser[a]) = new Parser[unit] {
def apply(in: inputType): Result = p.apply(in) match {
case None => Some(Pair((), in))
case Some(_) => None
}
}
def succeed[a](x: a) = new Parser[a] {
def apply(in: inputType): Result = Some(Pair(x, in))
}
def rep[a](p: Parser[a]): Parser[List[a]] =
rep1(p) ||| succeed(List());
def rep1[a](p: Parser[a]): Parser[List[a]] =
for (val x <- p; val xs <- rep(p)) yield x :: xs;
def repWith[a, b](p: Parser[a], sep: Parser[b]): Parser[List[a]] =
for (val x <- p; val xs <- rep(sep &&& p)) yield x :: xs;
def opt[a](p: Parser[a]): Parser[List[a]] =
(for (val x <- p) yield List(x)) ||| succeed(List());
}
|