[https://github.com/Yardanico/nim-mathexpr](https://github.com/Yardanico/nim-mathexpr)

This is a mathematic expression evaluator library in pure Nim (with no 
third-party dependencies).

Basically it is a recursive descent evaluator.

It supports many mathematical functions, also you can provide variables and add 
custom functions.

Also it doesn't have strict rules on arguments, so all of these are valid:
    
    
    sqrt(max(1, 2))
    sqrt(max(1 2))
    sqrt max(1, 2)
    sqrt max(1 2)
    
    # You can even do something like this!
    sqrt fac log2 10
    

Example REPL: 
    
    
    ## An example REPL for Mathexpr:
    import strutils, rdstdin, ./mathexpr, tables
    
    # Our variables (they will be available in the REPL)
    var ourVars = {"x": 5.0, "y": 6.0, "z": 75.0}.newTable()
    
    # Procedure should have this type:
    # proc(args: seq[float]): float
    proc mySum(args: seq[float]): float =
      for arg in args: result += arg
    
    # Add our custom `sum` function
    mathexpr.functions["sum"] = mySum
    
    while true:
      var expr: string
      try:
        expr = readLineFromStdin("> ")
      except IOError:
        echo "Goodbye!"
        quit()
      
      if expr in ["exit", "quit", "quit()", "exit()"]:
        quit(0)
      try:
        let result = eval(expr, ourVars)
        echo "$1 = $2" % [expr, $result]
      except:
        echo getCurrentExceptionMsg()
        continue
    

By the way, implementation is less than 200 lines and it works in JS backend 

Reply via email to