简体   繁体   中英

RE: Error encountered in ramda-fantasy map method

I am trying to understand how the map works in FP. I want to test how does the map work in Functional Programming.

Below is the testing code.

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) 

I think it is the same M.of(20).map(a2) === a2(M.of(20))

Well, no, it's not. When you map a function over a data structure, it will be called with the contained values - in this case, 20 . And a2(20) throws the error you are getting.

What you can do instead, for example, is M.of(20).map(R.inc) - the result would be Just {value: 21} , while M.Nothing().map(R.inc) will yield Nothing .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM