liveBook · Manning

Fmap

As explained in Functional Programming in JavaScript

A mapping operation for a functor that applies a function to the wrapped value and returns a new functor of the same type.

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

How Functional Programming in JavaScript covers it

How deep it goes
Defines fmap, implements it in Wrapper, and demonstrates chained transformations, but does not develop formal functor laws.
Examples
Demonstrates Wrapper values, incrementing 2 to 5, chaining to 15, identity extraction, and logging with tap.
What it assumes
Assumes basic JavaScript functions and arrays’ map, while introducing wrappers and functor mapping through concrete examples.
What you can do after
Build it from scratch by implementing Wrapper.fmap and chain transformations without directly accessing the wrapped value.
How it connects
Connects fmap with functors, map, wrappers, identity functions, currying, and function composition.

Also explained in

Compare how 3 books explain fmap →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Functional Programming in JavaScript. The section links point to the parts of the book it draws on.