javascript - Ramda `cond` else 语句

标签 javascript functional-programming ramda.js

我正在查看Ramda 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'

我理解该函数的[谓词,变换]方面,但我不清楚“else”部分是如何工作的。在典型的 if/else-if/else 语句中,“else”部分不接受谓词。然而,在该示例中,每个数组都有一个谓词。也许了解 R.T 在这种情况下如何运作会有所帮助,但在文档中搜索 T 却毫无结果。

如何使用 Ramda 的 cond 函数捕获条件“else”功能以返回默认值?

最佳答案

R.T 始终返回 true 并忽略传递给它的任何参数。 这就是您传入的 100 被忽略并且仅返回 true 的原因。

R.cond 搜索每个[谓词,变换] 对,并停止搜索第一个计算结果为true 的谓词。 因此,将评估 [谓词,变换] 对中的第一个匹配实体。

如果没有任何内容为 true,则它到达末尾并执行 R.T 谓词(始终为 true),其作用类似于列表的其他部分。

关于javascript - Ramda `cond` else 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38150870/

相关文章:

javascript - 按嵌套键对数组进行分组

javascript - lambda 斯 : locating items with an inner array that satisfies a spec

javascript - 如何在 TypeScript 中导出 Ramda 柯里化(Currying)函数?

c++ - 我可以在这里使用模板特化或类型强制吗?

javascript - 当标签或窗口不活动时,浏览器如何暂停/更改 Javascript?

javascript - 如何防止将拖动的项目掉落在特定位置/区域?

javascript - Fullcalendar jquery 插件高度问题

scala - 为什么这个 Scala 行返回一个单位?

ios - RACStream 代表一个 monad 是什么意思?

javascript - Twitter API 回复 (in_reply_to_status_id) 无法正常工作