Created
July 9, 2016 21:45
-
-
Save psylone/200f7d916af78ba01a87014564235584 to your computer and use it in GitHub Desktop.
Ruby evaluation strategy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def procedure | |
procedure | |
end | |
def test_evaluation_strategy(x, y) | |
x == 0 ? 0 : y | |
end | |
test_evaluation_strategy(0, procedure) | |
# Explanation | |
# | |
# We get `stack level too deep (SystemStackError)` because of applicative-order evaluation strategy. Ruby interpreter at first computes the arguments and only after that passes them into the `test_evaluation_strategy` method. So the call of `0` is just a zero and the `procedure` call gives an infinite recursion. | |
# | |
# The other hand, if the Ruby interpreter followed the normal-order evaluation strategy, we would have `0` as the result. That's due to the fact that in the normal-order evaluation interpreter first makes a substitution of the method and its arguments with their expressions and only after that computes the result. Thus after the substitution our method transforms to this: | |
# | |
# 0 == 0 ? 0 : procedure | |
# | |
# So the result of this expression is `0`. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment