Skip to content

Instantly share code, notes, and snippets.

@tkojitu
Last active December 11, 2015 22:19
Show Gist options
  • Save tkojitu/4668888 to your computer and use it in GitHub Desktop.
Save tkojitu/4668888 to your computer and use it in GitHub Desktop.
from "The AWK Programming Language" (A.V.Aho, B.W.Kernighan, P.J.Weinberger) recursive descendent parser
# from "The AWK Programming Language" (A.V.Aho, B.W.Kernighan, P.J.Weinberger)
# recursive descendent parser
def expr
e = term
while $tokens[$index] == "+" || $tokens[$index] == "-"
$index += 1
e = ($tokens[$index - 1] == "+") ? e + term : e - term
end
return e
end
def term
e = factor
while $tokens[$index] == "*" || $tokens[$index] == "/"
$index += 1
e = ($tokens[$index - 1] == "*") ? e * factor : e / factor
end
return e
end
def factor
if $tokens[$index] =~ /^[+-]?(\d+\.?\d*|\.\d+)$/
$index += 1
return $tokens[$index - 1].to_f
elsif $tokens[$index] == "("
$index += 1
e = expr
$index += 1
if $tokens[$index - 1] != ")"
$stdout.printf("error: missing ) at %s\n", $tokens[$index])
end
return e
else
$stdout.printf("error: expected number or ( at %s\n", $tokens[$index])
return 0
end
end
while (line = $stdin.gets)
$index = 0
$tokens = line.split
e = expr()
if $index < $tokens.size
$stdout.printf("error at %s\n", $tokens[$index])
else
$stdout.printf("\5%.8g\n", e)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment