Last active
August 29, 2015 14:03
-
-
Save johnmyleswhite/078f376df2bac46f51f4 to your computer and use it in GitHub Desktop.
Function Evaluation in Julia and R: Example 1.5 from SICP
This file contains 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
# Ben Bitdiddle's demonstration that Julia uses applicative-order evaluation | |
p() = p() | |
# p (generic function with 1 method) | |
test(x, y) = x == 0 ? 0 : y | |
# test (generic function with 1 method) | |
test(0, p()) | |
# ERROR: stack overflow | |
# in p at none:1 (repeats 80000 times) |
This file contains 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
# In contrast, R uses a form of delayed evaluation that is more similar | |
# to normal-order evaluation | |
p <- function() {p()} | |
test <- function(x, y) { | |
if (x == 0L) { | |
return(0L) | |
} else { | |
return(y) | |
} | |
} | |
test(0L, p()) | |
# [1] 0 |
This file contains 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
# Like Julia, Python also uses applicative-order evaluation | |
def p(): | |
p() | |
def test(x, y): | |
if x == 0: | |
return 0 | |
else: | |
return y | |
test(0, p()) | |
# Traceback (most recent call last): | |
# File "<stdin>", line 1, in <module> | |
# File "<stdin>", line 2, in p | |
# [...] | |
# File "<stdin>", line 2, in p | |
# RuntimeError: maximum recursion depth exceeded |
This file contains 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
# Like Julia and Python, Ruby also uses applicative-order evaluation | |
def p() | |
p() | |
end | |
def test(x, y) | |
if x == 0 | |
return 0 | |
else | |
return y | |
end | |
end | |
test(0, p()) | |
# SystemStackError: stack level too deep | |
# from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/irb/workspace.rb:86 | |
# Maybe IRB bug! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment