Ramda `cond` else 语句
Ramda `cond` else statement
我正在查看 Ramda docs for the cond
function 并且对其行为感到困惑。文档指出 cond
...
Returns a function, fn, which encapsulates if/else-if/else logic.
R.cond takes a list of [predicate, transform] pairs. All of the
arguments to fn are applied to each of the predicates in turn until
one returns a "truthy" value, at which point fn returns the result of
applying its arguments to the corresponding transformer. If none of
the predicates matches, fn returns undefined.
这里是给出的例子:
var fn = R.cond([
[R.equals(0), R.always('water freezes at 0°C')],
[R.equals(100), R.always('water boils at 100°C')],
[R.T, temp => 'nothing special happens at ' + temp + '°C']
]);
fn(0); //=> 'water freezes at 0°C'
fn(50); //=> 'nothing special happens at 50°C'
fn(100); //=> 'water boils at 100°C'
我了解函数的 [predicate, transform]
方面,但我不清楚 "else" 部分是如何工作的。在典型的 if/else-if/else 语句中,"else" 部分不接受谓词。然而,在示例中,每个数组都有一个谓词。也许知道 R.T
在这种情况下如何运作会有所帮助,但在文档中搜索 T
是没有结果的。
如何使用 Ramda 的 cond
函数来捕获条件 "else" 功能以便 return 默认值?
R.T
始终 returns true
并忽略传递给它的任何参数。
这就是您传入的 100
被忽略并返回 true
.
的原因
R.cond
搜索每个 [predicate, transform]
对,并停止搜索计算结果为 true
的第一个谓词。
因此,将评估 [predicate, transform]
对中的第一个匹配实体。
如果没有 true
,则它到达末尾并执行 R.T
谓词(始终为 true
),其作用类似于列表的 else 部分。
我正在查看 Ramda docs for the cond
function 并且对其行为感到困惑。文档指出 cond
...
Returns a function, fn, which encapsulates if/else-if/else logic. R.cond takes a list of [predicate, transform] pairs. All of the arguments to fn are applied to each of the predicates in turn until one returns a "truthy" value, at which point fn returns the result of applying its arguments to the corresponding transformer. If none of the predicates matches, fn returns undefined.
这里是给出的例子:
var fn = R.cond([
[R.equals(0), R.always('water freezes at 0°C')],
[R.equals(100), R.always('water boils at 100°C')],
[R.T, temp => 'nothing special happens at ' + temp + '°C']
]);
fn(0); //=> 'water freezes at 0°C'
fn(50); //=> 'nothing special happens at 50°C'
fn(100); //=> 'water boils at 100°C'
我了解函数的 [predicate, transform]
方面,但我不清楚 "else" 部分是如何工作的。在典型的 if/else-if/else 语句中,"else" 部分不接受谓词。然而,在示例中,每个数组都有一个谓词。也许知道 R.T
在这种情况下如何运作会有所帮助,但在文档中搜索 T
是没有结果的。
如何使用 Ramda 的 cond
函数来捕获条件 "else" 功能以便 return 默认值?
R.T
始终 returns true
并忽略传递给它的任何参数。
这就是您传入的 100
被忽略并返回 true
.
R.cond
搜索每个 [predicate, transform]
对,并停止搜索计算结果为 true
的第一个谓词。
因此,将评估 [predicate, transform]
对中的第一个匹配实体。
如果没有 true
,则它到达末尾并执行 R.T
谓词(始终为 true
),其作用类似于列表的 else 部分。