Map and Evaluate the State

Take a look at the code from the previous section. So far, every time we need to modify the resultant, we need to use the constructors.

Instead, we can use the .map method to inject a function and to let the type itself take care of all the internal things for us.

To use the map method, let’s create a new constructor that will get us the current state.

const getState = () => State(state => Pair(state, state));

As you can see we have simply created an instance of State and return the state as both the resultant and the state.

Let’s use this in the log statement like this:

log(getState().runWith(1000).snd());

Running the node command in the terminal, we will get the output as 1000. Replacing the snd method with fst will also give us the output as 1000.

In the helpers.js file, create a new function called add that will take two numbers as input and return their sum as output.

const add = x => y => x + y;

We can then use this function inside the index.js file. First, import the add function into the index.js file.

const {add} = require('./helpers.js');

Then, use it inside the log statement like this:

log(getState().map(add(1000).runwith(1000).fst());

Run the node command and you will get 2000 as the ouput.

The amazing thing here is that the resultant is not constrained to a type like the state is. In fact, we can change the type of the resultant as we want. To understand this, create a new function in the helpers.js file called plural .

const plural = (single, multiple) => num =>

`${num} ${Math.abs(num) === 1 ? single : multiple}`

This function takes in a tuple of two strings as the context, takes another number as its data, and returns to a string. Import this function into the index.js file.

const {add, plural} = require('./helpers.js');

Use the plural function inside another function called amazingRajat .

const amazingRajat = plural('Rajat', 'Rajats');

Lets use this function inside the log statement as shown below.

log(getState()

.map(amazingRajat)

.runWith(1000)

.fst()

)

The ouput of this will be something like 1000 Rajats . If you replace the 1000 with 1, you will get the output as 1 Rajat .

Note: You can get rid the of getState by importing its replacement from the crocks library.