Skip to content

Maybe (Monad)

The Maybe type in PureEval may differ from the Data Maybe found in other functional languages like Haskell. In PureEval, Maybe is a fusion of Data Maybe and Class Monad.

Maybe

The Maybe type encapsulates a value that may be indeterminate.

If an operation on a specific value within Maybe fails, it turns into Nothing.

Both undefined and null are considered as Nothing.

  • Type

Maybe.of()

Lifts a value into a Maybe type.

  • Type
  • Example
js
Maybe.of(1); // Just 1
Maybe.of(null); // Nothing
Maybe.of(1); // Just 1
Maybe.of(null); // Nothing

Maybe.is()

Determines whether a value is of type Maybe.

  • Type
  • Example
js
Maybe.is(Just(1)); // true
Maybe.is(Nothing); // true
Maybe.is(Just(1)); // true
Maybe.is(Nothing); // true

Maybe.isNothing()

Determines if the Maybe is Nothing.

  • Type
  • Example
js
Just(1).isNothing(); // false
Just(null).isNothing(); // true
Just(1).isNothing(); // false
Just(null).isNothing(); // true

Maybe.map()

Maps the value inside Maybe through a function, constructing a new Maybe to hold the result.

  • Type
  • Example
js
Just(1).map(add(114513)); // Just 114514
Just(1).map(add(114513)); // Just 114514

Maybe.fold()

Applies a function to the value within Maybe a.

Takes two unary function parameters for handling cases when Maybe a is Nothing and when it is not.

  • Type
  • Example
js
Just('The body next door').fold(() => 'Nothing', id); // "The body next door"
Just('The body next door').fold(() => 'Nothing', id); // "The body next door"

Maybe.chain()

Chains a function that returns a Maybe type, allowing for method chaining.

  • Type
  • Example
js
// Example demonstrating method chaining using Maybe
// [...]
console.log(city); // 'Anytown'
// Example demonstrating method chaining using Maybe
// [...]
console.log(city); // 'Anytown'

Just()

Constructor function for the Maybe type.

Equivalent to Maybe.of.

  • Type
  • Example
js
Just(1); // Just 1
Just(1); // Just 1

Nothing

Constructor for the Maybe type representing the absence of a value.

PureEval released under the GPL-3.0 License.