progs/fun_parser.scala
changeset 655 3d04ee04966d
parent 645 30943d5491b6
child 699 7dac350b20a1
equal deleted inserted replaced
654:fb6192488b91 655:3d04ee04966d
    32 //    type parameter I needs to be of Seq-type
    32 //    type parameter I needs to be of Seq-type
    33 //
    33 //
    34 abstract class Parser[I, T](implicit ev: I => Seq[_]) {
    34 abstract class Parser[I, T](implicit ev: I => Seq[_]) {
    35   def parse(ts: I): Set[(T, I)]
    35   def parse(ts: I): Set[(T, I)]
    36 
    36 
    37   def parse_all(ts: I) : Set[T] =
    37   def parse_single(ts: I) : T = 
    38     for ((head, tail) <- parse(ts); if (tail.isEmpty)) yield head
    38     parse(ts).partition(_._2.isEmpty) match {
    39 
    39       case (good, _) if !good.isEmpty => good.head._1
    40   def parse_single(ts: I) : T = parse_all(ts).toList match {
    40       case (_, err) => { 
    41     case List(t) => t
    41 	println (s"Parse Error\n${err.minBy(_._2.length)}") ; sys.exit(-1) }
    42     case _ => { println ("Parse Error\n") ; sys.exit(-1) }
    42     }
    43   }
       
    44 }
    43 }
    45 
    44 
    46 // convenience for writing grammar rules
    45 // convenience for writing grammar rules
    47 case class ~[+A, +B](_1: A, _2: B)
    46 case class ~[+A, +B](_1: A, _2: B)
    48 
    47