Skip to content

Instantly share code, notes, and snippets.

@johnmyleswhite
Last active August 29, 2015 14:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnmyleswhite/078f376df2bac46f51f4 to your computer and use it in GitHub Desktop.
Save johnmyleswhite/078f376df2bac46f51f4 to your computer and use it in GitHub Desktop.
Function Evaluation in Julia and R: Example 1.5 from SICP
# 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)
# 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
# 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
# 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