【问题标题】:Is __ supposed to work only with curried functions? Why is it working here?__ 应该只适用于咖喱函数吗?为什么它在这里工作?
【发布时间】:2020-01-13 10:31:01
【问题描述】:

我试图理解为什么__ 在这段代码中可以正常工作:

function editAddress (id, addressId, model) {
    return BusinessService
      .getById(id)
      .then(unless(
        () => checkUrlValue(addressId, model.id),
        rejectWithError(InvalidData.error('Invalid address data: Address id is different from request'))
      ))
      .then(pipe(
        updateModel(__, 'addresses', model, 'id', addressId),
        juxt([ always(id), identity ]),
        apply(BusinessService.editById)
      ))
      .then(pipe(
        prop('addresses'),
        find(propEq('id', addressId))
      ))
  }
function updateModel (entity, property, model, attr, id) {
  return evolve({
    [property]: pipe(
      juxt([
        findIndex(propEq(attr, id)),
        pipe(
          find(propEq(attr, id)),
          mergeLeft(model)
        ),
        identity
      ]),
      apply(update)
    )
  })(entity)
}

既然调用的函数(updateModel)没有被柯里化,为什么__在这种情况下仍然有效?

【问题讨论】:

  • 有趣的问题。我从未见过这种行为,我是 Ramda 的创始人之一。 Will Jenkins 的回答解释了这一点,我的评论对此进行了扩展。但很高兴知道这会奏效。

标签: javascript node.js functional-programming ramda.js


【解决方案1】:

updateModel 没有被柯里化,但它正在返回一个名为 evolve 的函数的结果,该函数被柯里化了。第一个调用传入:

{
    [property]: pipe(
      juxt([
        findIndex(propEq(attr, id)),
        pipe(
          find(propEq(attr, id)),
          mergeLeft(model)
        ),
        identity
      ]),
      apply(update)
    )
}

然后使用 entity 调用此调用的结果,在您的情况下将是 __。如果没有看到evolve 的内部结构,就无法进一步理解代码。

【讨论】:

  • 有趣,我从来没有注意到这种行为。但解释完全正确。 evolve source_curry2 source 确实说明了原因。当您将占位符作为最后一个参数传递给evolve(或任何其他柯里化函数)时,它本质上是一个空操作,返回一个与您通过仅提供较早参数获得的函数等效的函数。但我以前从未见过这种做法。
  • 啊,有道理...感谢您的解释,每天都是上学日!
猜你喜欢
  • 2013-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-28
  • 2016-03-30
  • 1970-01-01
相关资源
最近更新 更多