gpt4 book ai didi

javascript - Node 柯里化(Currying)函数,并为其分配了惰性值

转载 作者:搜寻专家 更新时间:2023-11-01 00:13:44 25 4
gpt4 key购买 nike

我有一个函数...

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

我有一个值...

let someGlobalValue;

然后我有另一个 const 就像...

const curriedFunction = constant(someGlobalValue);

现在……当我这样做的时候……

someGlobalValue = 123;
consoleLog(curriedFunction());

输出是undefined

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

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

我需要能够在调用 curried 函数之前设置 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 变量命名不当。它不是柯里化(Currying)函数,所以这个名称只会让您感到困惑。

let someGlobalValue = 1

const impureFunction = () => someGlobalValue

console.log(impureFunction())
// 1

someGlobalValue = 2

console.log(impureFunction())
// 2

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

关于javascript - Node 柯里化(Currying)函数,并为其分配了惰性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56440492/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com