RPN calculator implementations in 61 languages
math.bas.bg
math.bas.bg
I try doing a simple 4 function calculator (*/+-) with parens and with two numerical addins (sometimes I pick sin/cos, sometimes I pick max( ....) and min( ...)
The RPN version is good since you need to create stack management in the core.
While this doesn't have the panache of "Write a web server in 3 lines of Ruby (oh don't forget those two 500 line libraries.) It does give you good example of the simple things you can do.
He also has a pretty good swath of languages, I'm always excited to see Awk, Lua and Python (my go to lanaguages) on the same page. I'll need to see if I can break out my COBOL skills and get a pull request made up.
void main() {
import std.stdio, std.string, std.algorithm, std.conv;
// Reduce the RPN expression using a stack
readln.split.fold!((stack, op)
{
switch (op)
{
// Generate operator switch cases statically
static foreach (c; "+-*/")
case [c]:
return stack[0 .. $ - 2] ~
mixin("stack[$ - 2] " ~ c ~
" stack[$ - 1]");
default: return stack ~ op.to!real;
}
})((real[]).init).writeln;
} main = interact $ unlines. map (show.calc) .lines
calc :: String -> [Float]
calc = foldl f [] . words
where
f (x:y:zs) "+" = (y + x):zs
f (x:y:zs) "-" = (y - x):zs
f (x:y:zs) "*" = (y * x):zs
f (x:y:zs) "/" = (y / x):zs
f xs y = read y : xs