Jensen's Device: Difference between revisions

Content added Content deleted
(omit from Go)
Line 570: Line 570:
=={{header|R}}==
=={{header|R}}==
R uses a [[wp:Evaluation_strategy#Call_by_need|call by need]] evaluation strategy where function inputs
R uses a [[wp:Evaluation_strategy#Call_by_need|call by need]] evaluation strategy where function inputs
are evaluated on demand and then cached; functions can bypass the normal argument evaluation by using functions <tt>substitute</tt> and <tt>match.call</tt> to access the parse tree of the as-yet-unevaluated arguments, and using <tt>parent.frame</tt> to access the scope of the caller. There are some proposed
are lazily evaluated and then cached; functions can implement
nonstandard evaluation such as call-by-name by using the "substitute" primitive to
access the parse tree of the unevaluated input. There are some proposed
[http://developer.r-project.org/nonstandard-eval.pdf conventions] to do this in a way that is less confusing to the user
[http://developer.r-project.org/nonstandard-eval.pdf conventions] to do this in a way that is less confusing to the user
of a function. The following ignores any conventions to mimic the effect
of a function; however, ignoring conventions we can come disturbingly close to the ALGOL call-by-name semantics.
of the original ALGOL where "i" is truly assigned in the calling context.


<lang R>sum <- function(var, lo, hi, term)
<lang R>
eval(substitute({
sum <- function(var, lo, hi, term) {
s <- 0
.temp <- 0;
for (i in lo:hi) {
for (var in lo:hi) {
.temp <- .temp + term
eval.parent(substitute(x <- i, list(x=substitute(var), i=i)))
}
s <- s + eval.parent(substitute(term))
}
.temp
}, as.list(match.call()[-1])),
s
enclos=parent.frame())
}


print(sum(i, 1, 100, 1/i))
sum(i, 1, 100, 1/i) #prints 5.187378

</lang>
##and because of enclos=parent.frame(), the term can involve variables in the caller's scope:
x <- -1
sum(i, 1, 100, i^x) #5.187378</lang>


=={{header|REXX}}==
=={{header|REXX}}==