Skip to content

Commit

Permalink
-- few signatures
Browse files Browse the repository at this point in the history
  • Loading branch information
djnzx committed Jun 20, 2024
1 parent 3056fca commit 9dc1228
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 11 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,24 +8,30 @@ trait AbstractMathParser[A] {
val R = Reference
import R._

def process[EA >: Expr[A]](t: (EA, Seq[(Char, EA)])): EA = t match {
def combine[EA >: Expr[A]](t: (EA, Seq[(Char, EA)])): EA = t match {
case (n, Nil) => n
case (a, l) => l.foldLeft(a) { case (acc, (op, x)) => mkNode(op, acc, x) }
case (a, l) => l.foldLeft(a) { case (acc, (op, x)) => mkNode(op, acc, x) }
}

val plusOrMinus: Parser[Char] = char('+') | char('-')
val mulOrDiv: Parser[Char] = char('*') | char('/')
val `+|-` : Parser[Char] = char('+') | char('-')
val `*|/` : Parser[Char] = char('*') | char('/')

/** this is what we call value: integer.map(x => Value(x)) */
def value: Parser[Expr[A]]

/** whatever between parens */
def parens: Parser[Expr[A]] = surround(char('('), char(')'))(addSubSeq)

def term: Parser[Expr[A]] = value | parens

/** recursive grammar */
def parens = surround(char('('), char(')'))(addSub)
def factor = value | parens
def mulDivSeq: Parser[Expr[A]] = (term ** (`*|/` ** term).many) // (Expr[A], List[(Char, Expr[A])])
.map(combine)

def divMul = ( factor ** (mulOrDiv ** factor).many ).map(process)
def addSub: Parser[Expr[A]] = ( divMul ** (plusOrMinus ** divMul).many ).map(process)
def addSubSeq: Parser[Expr[A]] = (mulDivSeq ** (`+|-` ** mulDivSeq).many) // (Expr[A], List[(Char, Expr[A])])
.map(combine)

/** root of grammar */
def built = root(addSub)
def built: Parser[Expr[A]] = root(addSubSeq)

}
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
package fp_red.red09.p2concrete.math_num

import fp_red.red09.p0trait.ParseError
import fp_red.red09.p1impl.Reference
import fp_red.red09.p2concrete.math.BiTree
import org.scalatest.matchers.should.Matchers
import org.scalatest.funspec.AnyFunSpec

// 1
class MathOpToNumberSpec extends AnyFunSpec with Matchers {
val R = Reference

Expand All @@ -21,7 +22,11 @@ class MathOpToNumberSpec extends AnyFunSpec with Matchers {
"1-2*3",
"(1-2)*-3",
"((1-2)*(3+4))/5-1",
).foreach { s => pprint.log(R.run(built)(s)) }
).foreach { input =>
val parser: String => Either[ParseError, BiTree.Expr[Int]] = R.run(built)
val parsed: Either[ParseError, BiTree.Expr[Int]] = parser(input)
pprint.log(parsed)
}
}
}

Expand Down

0 comments on commit 9dc1228

Please sign in to comment.