【问题标题】:RE: Error encountered in ramda-fantasy map methodRE: ramda-fantasy map 方法遇到错误
【发布时间】:2017-08-13 23:45:55
【问题描述】:

我试图了解地图在 FP 中的工作原理。我想测试一下地图在函数式编程中是如何工作的。

下面是测试代码。

var R = require('ramda');
var M = require('ramda-fantasy').Maybe;
var Just = M.Just;
var Nothing = M.Nothing;
var safeDiv = R.curry(function (n, d) { return d === 0 ? Nothing() : Just(n / d); });
var lookup = R.curry(function (k, obj) { return k in obj ? Just(obj[k]) : Nothing(); });
var a2 = M.maybe(100, R.inc);
var a4 = M.of(10);
console.log(a2); //output [Function]
console.log(a4); //output Just{ value: 10}
console.log(a2(Nothing())); //output 100
console.log(a2(M.of(20))); //out 21
// This is why I can't understand
// I think it is the same M.of(20).map(a2) === a2(M.of(20)).
console.log(M.of(20).map(a2));
// Produce the followng error message
// /mnt/e/work/fpjs/node_modules/ramda-fantasy/src/Maybe.js:49
// return m.reduce(function(_, x) {
//     TypeError: m.reduce is not a function
//     at /mnt/e/work/fpjs/node_modules/ramda-fantasy/src/Maybe.js:49:12
//     at /mnt/e/work/fpjs/node_modules/ramda/src/internal/_curryN.js:37:27
//     at /mnt/e/work/fpjs/node_modules/ramda/src/internal/_arity.js:5:45
//     at Just.map (/mnt/e/work/fpjs/node_modules/ramda-fantasy/src/Maybe.js:56:18)
//     at Object.<anonymous> (/mnt/e/work/fpjs/data/test3.js:14:22)
//     at Module._compile (module.js:571:32)
//     at Object.Module._extensions..js (module.js:580:10)
//     at Module.load (module.js:488:32)
//     at tryModuleLoad (module.js:447:12)
//     at Function.Module._load (module.js:439:3) 

【问题讨论】:

    标签: javascript functional-programming ramda-fantasy


    【解决方案1】:

    我认为是一样的M.of(20).map(a2) === a2(M.of(20))

    嗯,不,不是。当您在数据结构上map 一个函数时,将使用包含的值调用它 - 在本例中为20a2(20) 会抛出你得到的错误。

    例如,您可以改为使用M.of(20).map(R.inc) - 结果将是Just {value: 21},而M.Nothing().map(R.inc) 将产生Nothing

    【讨论】:

      猜你喜欢
      • 2017-02-14
      • 2017-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-22
      • 2018-04-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多