Hacker Newsnew | past | comments | ask | show | jobs | submitlogin
RPN calculator implementations in 61 languages (bas.bg)
85 points by nkurz on Jan 1, 2019 | hide | past | favorite | 8 comments


I love things like this. While 99 bottles of beer is pretty simple, applications like this give you a slightly better look at the language.

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.


This is really cool, I think I would like to do this as an exercise with a similar small program. Does he have some sort of write-up after making all these talking about the individual languages?


The D version currently on display on the website (Which I wrote, minus the use of static foreach):

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;
}


So, haskell version may be little shorter

  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



I expected the javascript implementation to be a oneliner with Array reduce operation.


I was very disappointed that the JS implementation leans on eval(). That's kind of cheating, no?


Love using RPN




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: