Maybe class "map" function doesn't compose

Author: ChuckJonasCreated Mar 26, 2021Updated Mar 24, 2025

In chapter 8, Maybe is defined as follows:

javascript
class Maybe {
  static of(x) {
    return new Maybe(x);
  }

  get isNothing() {
    return this.$value === null || this.$value === undefined;
  }

  constructor(x) {
    this.$value = x;
  }

  map(fn) {
    return this.isNothing ? this : Maybe.of(fn(this.$value));
  }

  inspect() {
    return this.isNothing ? 'Nothing' : `Just(${inspect(this.$value)})`;
  }
}

Then an example is provided using a . style:

javascript
Maybe.of({ name: 'Boris' }).map(prop('age')).map(add(10));
// Nothing

However, it's been brought to my attention that this is not a "lawful" use of a functor because it doesn't compose?

javascript
const f = (v) => v.name;
const g = JSON.stringify;
const fandTheng = (a) => g(f(a));
const user = { name: null };
console.log(
  Maybe.of(user).map(f).map(g).inspect(),  // Nothing 
  Maybe.of(user).map(fandTheng).inspect()  // Just(null) 
); // not equal, breaks the law of composition!

I haven't finished the book so sorry if this is address further on.

PS: I think the inspect method has a bug in the recursion as this example will break it.

Source: MostlyAdequate/mostly-adequate-guide