How to resolve the algorithm Arithmetic evaluation step by step in the jq programming language

Published on 12 May 2024 09:40 PM
#Jq

How to resolve the algorithm Arithmetic evaluation step by step in the jq programming language

Table of Contents

Problem Statement

For those who don't remember, mathematical precedence is as follows:

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Arithmetic evaluation step by step in the jq programming language

Source code in the jq programming language

def star(E): (E | star(E)) // .;
def plus(E): E | (plus(E) // . );
def optional(E): E // .;
def amp(E): . as $in | E | $in;
def neg(E): select( [E] == [] );

def literal($s):
  select(.remainder | startswith($s))
  | .result += [$s]
  | .remainder |= .[$s | length :] ;

def box(E):
   ((.result = null) | E) as $e
   | .remainder = $e.remainder
   | .result += [$e.result]  # the magic sauce
   ;

# Consume a regular expression rooted at the start of .remainder, or emit empty;
# on success, update .remainder and set .match but do NOT update .result
def consume($re):
  # on failure, match yields empty
  (.remainder | match("^" + $re)) as $match
  | .remainder |= .[$match.length :]
  | .match = $match.string ;

def parseNumber($re):
  consume($re)
  | .result = .result + [.match|tonumber] ;

def Expr:

  def ws: consume(" *");

  def Number: ws | parseNumber( "-?[0-9]+([.][0-9]*)?" );
  
  def Sum:
    def Parenthesized: ws | consume("[(]") | ws | box(Sum) | ws | consume("[)]");
    def Factor: Parenthesized // Number;
    def Product: box(Factor | star( ws | (literal("*") // literal("/")) | Factor));
    Product | ws | star( (literal("+") // literal("-")) | Product);

  Sum;

# Left-to-right evaluation
def eval:
  if type == "array" then
    if length == 0 then null
    else .[-1] |= eval
    | if length == 1 then .[0]
      else (.[:-2] | eval) as $v
      | if   .[-2] == "*" then $v * .[-1]
        elif .[-2] == "/" then $v / .[-1]
        elif .[-2] == "+" then $v + .[-1] 
        elif .[-2] == "-" then $v - .[-1] 
        else tostring|error
	end
      end
    end
  else .
  end;

def eval(String):
  {remainder: String}
  | Expr.result
  | eval;

  

You may also check:How to resolve the algorithm Colour bars/Display step by step in the PHP programming language
You may also check:How to resolve the algorithm Gapful numbers step by step in the D programming language
You may also check:How to resolve the algorithm Variables step by step in the J programming language
You may also check:How to resolve the algorithm Day of the week step by step in the Fortran programming language
You may also check:How to resolve the algorithm Walk a directory/Recursively step by step in the REXX programming language