Skip to content

Instantly share code, notes, and snippets.

@baweaver

baweaver/rpn_calc.rb

Last active Aug 29, 2015
Embed
What would you like to do?
Reverse polish notation from Ox0dea
@_=[*?/...?:][(_=$$/$$)..-_]*'';(@__=->__{$_=__[_-_];@_[$_]?$*<<(@_=~/#$_/):(___,$__=$*[-_-_,_+_];$*[-_-_,_+_]=$_[?+]?___+$__:$_[?-]?___-$__:$_[?*]?___*$__:$_[?/]?___/$__:_);__[_]?@__[__[_..-_]]:$*})
# Here we go again! Note - THIS NEEDS REFINEMENT when I have more than a few minutes to look at it
@_ =
# Range of 0 to 9, joined into a string: '0123456789'
[*?/...?:][
# deriving 1 from PID / PID, to -1 (negative of that)
# then joining with the * ''
(_ = $$/$$)..-_
] * ''
# Y Combinator hack again, which takes a single arg:
# __ is a string
(@__ = -> __ {
# $_ is the first character of the string (__[0])
$_ = __[_-_]
# Check if the string still contains the character
@_[$_] ?
# $* is ARGV, which is an empty array at this point
#
# so we're concatting the position of the last character onto the array
$* << (@_ =~ /#$_/) :
(
# So we're getting an array back and splatting it which is composed of
# the last two characters of the array $*
#
# If there aren't two characters we have
# ___ is nil
# $-- is nil
___, $__ = $*[-_-_, _+_];
# Noted this breaks if you linebreak here, but for the sake of explaining...
#
# If the first character is a plus, 'pop' the last two characters and replace them with:
$*[-_-_,_+_] = $_[?+] ?
# the result of their addition
___ + $__ :
# or the result of their subtraction
$_[?-] ?
___ - $__ :
# or multiplication
$_[?*] ?
___ * $__ :
# or division
$_[?/] ? ___ / $__ :
# or just 1
_
)
# Recurse if the accumulator isn't out of bounds
__[_] ?
# if not out of bounds, recall with strings tail
@__[__[_..-_]] :
# else return the accumulator
$*
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.