chain

Transforms an entire Maybe structure with the provided function. As with .map(), the transformation is only applied if the value is a Just, but unlike .map() the transformation is expected to return a new Maybe value.

Signature

forall a, b: (Maybe a).((a) => Maybe b) => Maybe b

Documentation

Transforms an entire Maybe structure with the provided function. As with .map(), the transformation is only applied if the value is a Just, but unlike .map() the transformation is expected to return a new Maybe value.

Having the transformation function return a new Maybe value means that the transformation may fail, and the failure is appropriately propagated. In this sense, a.chain(f) works similarly to the sequencing of statements done by the ; syntax in JavaScript — the next instruction only runs if the previous instruction succeeds, and either instructions may fail.

Example:

const Maybe = require('folktale/maybe');

function first(list) {
  return list.length > 0 ?  Maybe.Just(list[0])
  :      /* otherwise */    Maybe.Nothing();
}

first([]).chain(first);
// ==> Maybe.Nothing()

first([[1]]).chain(first);
// ==> Maybe.Just(1)

first([[]]).chain(first);
// ==> Maybe.Nothing()

Properties

Source Code

Defined in source/maybe/maybe.js at line 57, column 18
{
    /*~*/
    Nothing: function chain(transformation) {
      assertFunction('Maybe.Nothing#chain', transformation);
      return this;
    },

    /*~*/
    Just: function chain(transformation) {
      assertFunction('Maybe.Just#chain', transformation);
      return transformation(this.value);
    }
  }
Stability
stable
Licence
MIT
Module
folktale/maybe/maybe
Authors
Copyright
(c) 2013-2017 Quildreen Motta, and CONTRIBUTORS
Authors
  • Quildreen Motta
Maintainers
  • Quildreen Motta <queen@robotlolita.me> (http://robotlolita.me/)