我试图了解地图在 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)