[英]Order of evaluation javascript
I am tasked to write a function f in javascript, and 我负责用JavaScript编写函数f,并且
f(0)+f(1)//should return 0 if evaluated from left to right
//should return 1 if evaluated from right to left
How can I implement the function f? 如何实现函数f? I am thinking about keeping track of whether f is called before, but have no idea how. 我正在考虑跟踪是否曾经调用过f,但不知道如何调用。
The scheme solution is as following: 方案解决方案如下:
(define f (let ((set #f)) (define (fn n) (if set 0 (begin (set! set #t) n))) fn)) (定义f(let((set #f))(define(fn n)(如果set 0(开始(set!set #t)n)))fn))
The Scheme solution seems to come down to Scheme解决方案似乎可以归结为
var f = (function() {
var set = false;
function fn(n) {
if (set) {
return 0;
} else {
set = true;
return n;
}
}
return fn;
}());
which is a bit boring but expected. 这有点无聊但可以预期。 Yes, you need to keep track of the state somewhere outside of f
, declaring an extra variable is the simplest solution. 是的,您需要在f
之外的某个位置跟踪状态,声明额外的变量是最简单的解决方案。 It doesn't need to be global though, set
is hidden in the scope of the IIFE. 尽管它不必是全局的,但是set
隐藏在IIFE的范围内。
Solution with a property of the function. 具有函数属性的解决方案。
function f(v) { return [f.value || 0, f.value = v][0]; } console.log(f(0) + f(1)); // 0
function f(v) { return [f.value || 0, f.value = v][0]; } console.log(f(1) + f(0)); // 1
I'm sure there's a shorter version... 我敢肯定有一个较短的版本...
function f(arg) {
if (!f.called && arg === 0) {
f.called = true;
return 0;
} else if (f.called && arg === 1) {
return 1;
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.