The Maybe Data Type

Create an empty folder in your system. You may name it anything you want.

$ mkdir maybe

$ cd maybe

Open this folder in a code editor. I like to use VS Code.

$ code .

Create a file named utils.js file and write a simple utility function inside it.

const inc = n => n + 1 module.exports = {

inc

}

Here, the inc function takes in a number, increments it by one and returns it as the result.

Create another file called index.js and import the inc function inside it.

const {inc} = require('./utils') const input = 2;

const result = inc(input);

console.log(result);

Run this code in your terminal using the command node index.js and you will get the output as 3 .

But what if you give a string as the input? In the index.js file, pass any string to the input and run the node index.js command.

What you will get the as the output is the same string, but with a 1 attached to it. This happens because the plus operator now acts like a concatenator.

Change the value of input to undefined , and now your result will be a NaN . To avoid this obstacle, we can add a conditional statement that checks the typeof the input .

const result = typeof input === 'number' ? inc(input) : 0

While this works, we can do something much better with the help of maybe data type. Import a new library into this module called crocks .

$ yarn add crocks

This library contains the Maybe data type inside it. Import this library inside index.js file.

const Maybe = require('crocks/Maybe')

Maybe is an object that wraps a value and lets us differentiate between values that we want to act on and value that we do not want to act on. The reason this works is that Maybe is made up of two underlying types and it can be any one of those at a time.

Maybe is made up of a Just and Nothing type. Just is a value that we want our code to work on, and Nothing is the value that we want our code to ignore.

Inside index.js file, rewrite the code inside it using the Maybe data type.

const input = Maybe.Just (2);

const result = input.map (inc);

Running this code will get us the result as Just 3 . What happened is that we wrapped up our 2 in this Maybe . Then, when we called map on it to apply to that function, the Maybe unwrapped the value, got the 2 out and passed it into the inc function. The inc function then incremented it by 1, and passed it to result and wrapped it back up in the Just .

Replacing the value inside input with Maybe.Nothing() will give us the result as Nothing .

To use both of these types simultaneously, create a new function inside index.js called num and pass it to the input .

const num = val => typeof val === 'number' ? Maybe.Just(val) : Maybe.Nothing(); const input = num(2);

const result = input.map(inc);

console.log(result);