1 import scala.language.implicitConversions |
1 import scala.language.implicitConversions |
2 import scala.language.reflectiveCalls |
2 import scala.language.reflectiveCalls |
3 |
3 |
4 /* Note, in the lectures I did not show the implicit type consraint |
4 /* Note, in the lectures I did not show the implicit type |
5 * I => Seq[_], which means that the input type 'I' needs to be |
5 * constraint IsSeq, which means that the input type 'I' needs |
6 * a sequence. */ |
6 * to be a sequence. */ |
7 |
7 |
8 abstract class Parser[I, T](implicit ev: I => Seq[_]) { |
8 type IsSeq[A] = A => Seq[_] |
|
9 |
|
10 abstract class Parser[I : IsSeq, T] { |
9 def parse(ts: I): Set[(T, I)] |
11 def parse(ts: I): Set[(T, I)] |
10 |
12 |
11 def parse_all(ts: I) : Set[T] = |
13 def parse_all(ts: I) : Set[T] = |
12 for ((head, tail) <- parse(ts); |
14 for ((head, tail) <- parse(ts); |
13 if (tail.isEmpty)) yield head |
15 if (tail.isEmpty)) yield head |
14 } |
16 } |
15 |
17 |
16 class SeqParser[I, T, S](p: => Parser[I, T], |
18 class SeqParser[I : IsSeq, T, S](p: => Parser[I, T], |
17 q: => Parser[I, S])(implicit ev: I => Seq[_]) extends Parser[I, (T, S)] { |
19 q: => Parser[I, S]) extends Parser[I, (T, S)] { |
18 def parse(sb: I) = |
20 def parse(sb: I) = |
19 for ((head1, tail1) <- p.parse(sb); |
21 for ((head1, tail1) <- p.parse(sb); |
20 (head2, tail2) <- q.parse(tail1)) yield ((head1, head2), tail2) |
22 (head2, tail2) <- q.parse(tail1)) yield ((head1, head2), tail2) |
21 } |
23 } |
22 |
24 |
23 class AltParser[I, T](p: => Parser[I, T], |
25 class AltParser[I : IsSeq, T](p: => Parser[I, T], |
24 q: => Parser[I, T])(implicit ev: I => Seq[_]) extends Parser[I, T] { |
26 q: => Parser[I, T]) extends Parser[I, T] { |
25 def parse(sb: I) = p.parse(sb) ++ q.parse(sb) |
27 def parse(sb: I) = p.parse(sb) ++ q.parse(sb) |
26 } |
28 } |
27 |
29 |
28 class FunParser[I, T, S](p: => Parser[I, T], |
30 class FunParser[I : IsSeq, T, S](p: => Parser[I, T], |
29 f: T => S)(implicit ev: I => Seq[_]) extends Parser[I, S] { |
31 f: T => S) extends Parser[I, S] { |
30 def parse(sb: I) = |
32 def parse(sb: I) = |
31 for ((head, tail) <- p.parse(sb)) yield (f(head), tail) |
33 for ((head, tail) <- p.parse(sb)) yield (f(head), tail) |
32 } |
34 } |
33 |
35 |
34 // atomic parsers for characters, numbers and strings |
36 // atomic parsers for characters, numbers and strings |