Ron Ron - 3 months ago 6
Javascript Question

Should Maybe.map respect the mapped value?

For a Maybe.Just monad, if we map it with a function returning null, it will still return Just with null inside, but I think it should be Nothing, otherwise it lost its power to protect against null. Am I right, or there is another reason to be like that?

Maybe.fromNuallable({noname: ''}) // return Just({noname: ''})
.map(prop('name')) // return Just(undefined), but I think it should return Nothing()
.map(x=>x.length) // failed here


I checked all the implementations (falktale and ramda.fantasy) of Maybe.map, it is the below:

Just.prototype.map = function(f) {
return this.of(f(this.value));
};

Answer

Well, I might be wrong but map comes from Functors. So it operates on simple morphism not kleisli arrows. You need to use bind and some sort of a function that returns a monad

// maybeProp:: String -> A -> Maybe[B]
const maybeProp = name => val => Maybe.fromNullable(val[name])

Maybe
  .fromNullable({noname: ''})
  .bind(maybeProp('name'))
  .map(x => x.length)