Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7657401
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T13:01:24+00:00 2026-05-31T13:01:24+00:00

I’m new to Scala but I was wondering it it is possible to implement

  • 0

I’m new to Scala but I was wondering it it is possible to implement a simple Equation parser in the language.

Say I have a few functions (much like Excel functions):

IF(Cond a=b, val_true, val_false)

MID(String, Start_pos, num_chars) – string extract

LEN(String) – length of a string

OR(cond1, cond2, ... condn)

AND(cond1, cond2, ... condn)

So the idea would be I could pass in a formula at runtime as a string from a user as a command line argument along with any other params say IF(LEN(param1)=4,MID(param1,2,1), MID(param1,0,LEN(param1)))

The idea is to evaluate the function, so if the user provides that above formula and the string “scat” then the output would be “a”. If the string “scala” was given then the output would be “scala”…

How easy would this be to implement in Scala? What is the best design approach? I know there are no function pointers (in C I would have parsed the formula string into a collection of func points and gone from there)…

Any advice on how to approach this in efficient Scala style would be appreciated.

Cheers!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-31T13:01:26+00:00Added an answer on May 31, 2026 at 1:01 pm

    This question has motivated to experiment with combinator parsers. Given the following algebraic data types representing a subset of your expressions:

    import scala.util.parsing.combinator._
    object Expr { type VARS = Map[String, Any] }
    import Expr._
    sealed trait Expr { def eval(v: VARS) : Any } 
    
    case class If(cond: Cond, ifTrue: Expr, ifFalse: Expr) extends Expr {
      def eval(v: VARS) = 
        if (cond.eval(v)) ifTrue.eval(v) else ifFalse.eval(v)
    }
    case class Cond(left: Expr, right: Expr) extends Expr {
      def eval(v: VARS) = left.eval(v) == right.eval(v)
    }
    case class Len(ident: String) extends Expr { 
      def eval(v: VARS) = v(ident).toString.size
    }
    case class Mid(ident: String, start: Expr, count: Expr) extends Expr {
      def eval(v: VARS) = {
        val s = start.eval(v).asInstanceOf[Int]
        val e = s + count.eval(v).asInstanceOf[Int]
        v(ident).asInstanceOf[String].substring(s, e)
      }
    }
    case class Ident(ident: String) extends Expr   { def eval(v:VARS) = v(ident) }
    case class StringLit(value: String) extends Expr { def eval(v:VARS) = value }
    case class Number(value: String) extends Expr  { def eval(v:VARS) = value.toInt }
    

    The following parser definition will parse your given expression and return a Expr object:

    class Equation extends JavaTokenParsers {
      def IF: Parser[If] = "IF" ~ "(" ~ booleanExpr ~","~ expr ~","~ expr ~ ")" ^^ {
        case "IF" ~ "(" ~ booleanExpr ~ "," ~ ifTrue ~ "," ~ ifFalse ~ ")" =>
          If(booleanExpr, ifTrue, ifFalse)
      }
      def LEN: Parser[Len] = "LEN" ~> "(" ~> ident <~ ")" ^^ (Len(_))
      def MID: Parser[Mid] = "MID" ~ "(" ~ ident ~ "," ~ expr ~ "," ~ expr ~ ")" ^^ {
        case "MID" ~ "(" ~ ident ~ "," ~ expr1 ~ "," ~ expr2 ~ ")" =>
          Mid(ident, expr1, expr2) 
      }
      def expr: Parser[Expr] = (
        stringLiteral ^^ (StringLit(_))
        | wholeNumber  ^^ (Number(_))
        | LEN
        | MID 
        | IF 
        | ident ^^ (Ident(_))
      )
      def booleanExpr: Parser[Cond] = expr ~ "=" ~ expr ^^ {
        case expr1 ~ "=" ~ expr2 => Cond(expr1, expr2)
      }
    }
    

    Then parsing and evaluating the results can be done like this:

    val equation = new Equation
    val parsed = equation.parseAll(equation.expr,
       """IF(LEN(param1)=4,MID(param1,2,1), MID(param1,0,LEN(param1)))""")
    parsed match {
      case equation.Success(expr, _) =>
        println(expr)
        // If(Cond(Len(param1),Number(4)),
        //   Mid(param1,Number(2),Number(1)),
        //   Mid(param1,Number(0),Len(param1)))
        println(expr.eval(Map("param1" -> "scala"))) // prints scala
        println(expr.eval(Map("param1" -> "scat")))  // prints a
      case _ =>
        println("cannot parse")
    }
    

    Note that the grammar I provided is just the minimum to make your example parse and there absolutely no error management or type checking. Process wise, I first came up with a grammar without the production ^^ ... that would parse your example, then added the Expr types but without the eval method, then the production ^^ ..., then I finally added the eval methods to the Expr trait and sub-classes.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have just tried to save a simple *.rtf file with some websites and
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I have a French site that I want to parse, but am running into
This could be a duplicate question, but I have no idea what search terms
I have this code: - (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock { NSString *someString = [[NSString
I have a text area in my form which accepts all possible characters from
Seemingly simple, but I cannot find anything relevant on the web. What is the
I have a .ini file as follows: [playlist] numberofentries=2 File1=http://87.230.82.17:80 Title1=(#1 - 365/1400) Example
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
I have a jquery bug and I've been looking for hours now, I can't

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.