?

Log in

No account? Create an account
penrose orange

stephenw32768


/var/log/stephen

cat /var/log/stephen >/dev/eyes


2 dup sqr sqr sqr sqr swap /
penrose orange
stephenw32768
Command-line RPN calculator in Ruby.

I initially wanted a quick, easy one-line number base converter. Once that was written, it started gaining features, most of which I'll never actually use. It's not far off being a subset of FORTH...

Numbers are parsed as reals only if they contain a point; otherwise, they're treated as integers. Standard Ruby promotion rules apply: an operation on two ints yields an int; an operation on two reals yields a real; an operation on one of each yields a real. Bitwise operations and base conversions require ints; real arguments to these operations are silently converted to ints. Similarly, operations such as reciprocal only make sense on reals, so int arguments to them are silently promoted to reals.

Some "screenshots":

Print operations pop the stack. To preserve the stack after a print, duplicate the item at the top of the stack before printing:
[chryseis.~] rpn 3 1 2 + . +
3
stack underflow at argument 6 ("+")
[chryseis.~] rpn 3 1 2 + dup . +
3
6

Once all operations have been performed, anything left on the stack is
printed:
[chryseis.~] rpn 1 2 3 4 5 + .
9
3
2
1

Base conversion:
[chryseis.~] rpn 34 .x
0x22
[chryseis.~] rpn 34 .b
0b100010
[chryseis.~] rpn 0x22
34
[chryseis.~] rpn 0b100010
34

* is a special character in the shell, so has to be escaped. x is provided as a synonym:
[chryseis.~] rpn 47 2 \*
94
[chryseis.~] rpn 47 2 x
94

Lots of ways of calculating 32768:
[chryseis.~] rpn 2 15 pow
32768
[chryseis.~] rpn 2 15 pow .x
0x8000
[chryseis.~] rpn 1 15 shl
32768
[chryseis.~] rpn 2 dup sqr sqr sqr sqr swap /
32768

Area and circumference of a circle with radius 3.5 units:
[chryseis.~] rpn 3.5 dup sqr pi x . 2 pi x x
38.484510006475
21.9911485751286

A nice warm day on either side of the Atlantic:
[chryseis.~] rpn 28.0 ctof
82.4

I might embed this in a CGI script. It's been a while since I last wrote a web toy.