节点柯里化函数,并为其分配了惰性值

Node curried function with lazy value assigned to it

我有一个函数...

const constant = v => () => v;

我有一个值...

let someGlobalValue;

然后我还有一个 const 比如...

const curriedFunction = constant(someGlobalValue);

现在...当我这样做时...

someGlobalValue = 123;
consoleLog(curriedFunction());

输出为undefined

我知道这是为什么。这是因为我已经在加载文件时使用存储的值创建了柯里化函数的实例,并在此时设置了它。因此在调用柯里化函数时不会读取更改 someGlobalValue

但是...有没有办法不这样做?

我需要能够在调用 curried 函数之前设置 someGlobalValue 并将其设置为 return 我刚刚设置的值。但我不知道该怎么做。

谢谢

您可以交出对象引用,稍后在对象中设置值。但这是不可取的,因为它混淆了 reader.

const constant = o => () => o.value;
const someGlobalValue = {};
const curriedFunction = constant(someGlobalValue);

someGlobalValue.value = 123;

console.log(curriedFunction());

如果它确实是一个全局(或至少 in-scope)变量,并且在调用 curriedFunction 时需要它的 then-current 版本,则您不想柯里化功能。但是你说过你不能改变constant,所以你没有太多选择,必须及时咖喱,例如:

const curriedFunction = () => constant(someGlobalValue)();

每次调用时都会创建和丢弃一个函数,但如果您不能更改 constant,您就没有太多选择。幸运的是,JavaScript 引擎在这方面确实 很快。

Live Copy:

const constant = v => () => v;

let someGlobalValue;

const curriedFunction = () => constant(someGlobalValue)();

someGlobalValue = 123;
console.log(curriedFunction());

I have a function like...

const constant = v => () => v;

如果您想始终 return 一个常量值,这是一个很好的实用工具。但这不是你想要的。

最简单的解决方案:

const curriedFunction = () => someGlobalValue;

那么 curriedFunction() 将始终 return someGlobalValue 的值,即使您更改它也是如此。

I need to be able to set the someGlobalValue before calling the curried function and for it to return the value I just set. But I can't work out how to do this.

抱歉,这是功能性纪律的对立面。在函数式风格中,函数提供了引用透明性,即当给定相同的参数时,函数总是产生相同的结果。您描述的函数是不纯的,因为它会产生不同的结果,具体取决于 someGlobalValue.

的状态

另一个提示在于 constant 函数的名称。当我们使用 常量 时,程序员依赖于值 不会 改变的事实。

最后,您的 curriedFunction 变量命名不当。它不是柯里化函数,所以这个名字只会让你感到困惑。

let someGlobalValue = 1

const impureFunction = () => someGlobalValue

console.log(impureFunction())
// 1

someGlobalValue = 2

console.log(impureFunction())
// 2

你的问题在一小段代码上被放大了。如果您能分享更多背景信息并向我们展示您打算如何使用这些颗粒,我们或许能够提供更有效的建议。