fmap applies a function to a value inside a wrapper and returns a new wrapper of the same type. It changes the contained value without exposing or removing its protective context. section 5.2
Transforming a wrapped value
const two = wrap(2); two.fmap(plus3); // Wrapper(5) two.fmap(plus3).fmap(plus10); // Wrapper(15) Each call transforms the internal value and closes the result back into a Wrapper, so operations can be chained. section 5.2
Listing 5.1. Functional data type to wrap values
class Wrapper {
constructor(value) { #A
this._value = value;
}
// map :: (A -> B) -> A -> B
map(f) {
return f(this._value);
}
// fmap :: (A -> B) -> Wrapper[A] -> Wrapper[B]
fmap (f) { #B
return new Wrapper(f(this._value));
}
toString() {
return 'Wrapper (' + this._value + ')';
}
};
// wrap :: A -> Wrapper(A)
const wrap = (val) => new Wrapper(val); #C
module.exports = {
wrap: wrap,
Wrapper: Wrapper
};
The implementation shows fmap applying a function to the wrapped value and constructing a new Wrapper around the result. section 5.2
fmap is useful when:
- A value should remain encapsulated while being transformed safely and immutably. section 5.2
- Several transformations or side-effecting taps need to be composed around one wrapped value. section 5.2


