Advertisement
Guest User

Untitled

a guest
Jun 12th, 2014
182
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.27 KB | None | 0 0
  1. package it.vigtig.dm509.linearalgebra.dsl
  2.  
  3. import scala.util.parsing.combinator._
  4.  
  5. case class Coefficient(factor: Double, id: String)
  6. case class Line(lhs: List[Coefficient], rhs: Double)
  7.  
  8. trait LinearSystemDSL extends JavaTokenParsers with RegexParsers {
  9.  
  10.   def num: Parser[Double] = floatingPointNumber ^^ (_.toDouble)
  11.   def char: Parser[String] = """[a-zA-Z]""".r
  12.   def id: Parser[String] = char ~ rep(char | floatingPointNumber) ^^ (x => x._1 + x._2.mkString)
  13.   def op: Parser[String] = "+" | "-"
  14.   def factor: Parser[Coefficient] = ((num ~ id) | id) ^^ {
  15.     case (num: Double) ~ (id: String) => Coefficient(num, id)
  16.     case id: String => Coefficient(1d, id)
  17.   }
  18.   def lhs: Parser[List[Coefficient]] = factor ~ rep(op ~ factor) ^^ (x => x._1 :: x._2.map {
  19.     case "+" ~ f => f
  20.     case "-" ~ Coefficient(f, id) => Coefficient(-f, id)
  21.   })
  22.   def line: Parser[Line] = lhs ~ "=" ~ num ^^ {
  23.     case lhs ~ _ ~ rhs => Line(lhs, rhs)
  24.   }
  25.   def system: Parser[List[Line]] = rep(line)
  26.  
  27. }
  28.  
  29. object LinearSystemDSLTest extends App with LinearSystemDSL {
  30.  
  31.   val program =
  32.     """
  33.    2X + Y - Z = 8
  34.    -3X - Y + 2Z = -11
  35.    -2X + Y + 2Z = -3
  36.    """
  37.  
  38.   val pr = parseAll(system, program).get.mkString("\n")
  39.   println(parseAll(factor, "10.7X"))
  40.   println(pr)
  41.  
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement