.KeyWordIO.Strings.expression

Information

Syntax

             result = expression(string);
(result, nextIndex) = expression(string, startIndex=1, message="");

Description

This function is nearly the same as Examples.calculator. The essential difference is that function "expression" might be used in other parsing operations: After the expression is parsed and evaluated, the function returns with the value of the expression as well as the position of the character directly after the expression.

This function demonstrates how a simple expression calculator can be implemented in form of a recursive decent parser using basically the Strings.scanToken(..) and scanDelimiters(..) function. There are 2 local functions (term, primary) that implement the corresponding part of the grammar.

The following operations are supported (pi=3.14.. is a predefined constant):

   +, -
   *, /, ^
   (expression)
   sin(expression)
   cos(expression)
   tan(expression)
   sqrt(expression)
   asin(expression)
   acos(expression)
   atan(expression)
   exp(expression)
   log(expression)
   pi

The optional argument "startIndex" defines at which position scanning of the expression starts.

In case of error, the optional argument "message" is appended to the error message, in order to give additional information where the error occurred.

This function parses the following grammaer

  expression: [ add_op ] term { add_op term }
  add_op    : "+" | "-"
  term      : primary { mul_op primary }
  mul_op    : "*" | "/" | "^"
  primary   : UNSIGNED_NUMBER
              | pi
              | ( expression )
              | functionName( expression )
  function  :   sin
              | cos
              | tan
              | sqrt
              | asin
              | acos
              | atan
              | exp
              | log

Note, in Examples.readRealParameter it is shown, how the expression function can be used as part of another scan operation.

Example

  expression("2+3*(4-1)");  // returns 11
  expression("sin(pi/6)");  // returns 0.5

Interface

function expression
  extends Modelica.Icons.Function;
  import Modelica.Utilities.Types;
  import Modelica.Utilities.Strings;
  import Modelica.Math;
  import Modelica.Constants;
  input String string "Expression that is evaluated";
  input Integer startIndex = 1 "Start scanning of expression at character startIndex";
  input String message = "" "Message used in error message if scan is not successful";
  output Real result "Value of expression";
  output Integer nextIndex "Index after the scanned expression";
end expression;

Generated at 2024-03-28T19:15:55Z by OpenModelicaOpenModelica 1.22.3 using GenerateDoc.mos