Using State
Learn about using the State monad in our Retrieve Lambda. We’ll use this monad to check if the hotel ID is our test hotel.
We'll cover the following
We use a Reader to pass the configuration on to multiple functions. The railway model of always enriching our object with additional required information is an orderly way of thinking about functional programs. It means that we can avoid keeping the state within our application. That is, we don’t have to know that our request is now in the processed state or that information is contained within the object’s name, type, or properties. In some cases, though, we’ll need to keep State. This is why we use objects in OOP. How do we go about doing that in a functional language? Enter the State monad.
State monad
In essence, State provides a way for us to keep an object or value, which can be used and changed by our function. A classic example of the use of State is producing a random value. The way we generate a random number in OOP languages is often to call a built-in method that outputs a number within a given range. This means that we have a method that, given identical parameters, doesn’t produce the same output. We lose purity, which isn’t ideal. State is a way to solve this problem because it requires us to pass a seed value to a function. A different random value is produced depending on the seed. Pass in the same seed and we get the same value, saving purity.
In our case, we improvise a reason (not a very good one) to use State in our Retrieve Lambda. We use this monad to check if the hotel ID is our test hotel. If this is the case, we reduce the price to zero. That way, our testers don’t have to worry about paying when they’re just testing our code. If we don’t like this reason, think of our own, as necessary, justification.
The core fp-ts
library has several State flavors available, but the one we want (State plus TaskEither) isn’t among them. For that, we’ll need to add the fp-ts-contrib
package, another helper library, to our package.json
:
Get hands-on with 1200+ tech skills courses.