By rajaraodv
In Part 1, we talked through: Functional Programming basics, Currying, Pure Functions, āFantasy-landā specs, āFunctorsā, āMonadsā, āMaybe Monadsā and āEither Monadsā via couple of examples.
In this part, weāll cover: Applicative, curryN function and āValidation Applicativeā.
Thanks to FP gurus Brian Lonsdorf, keithalexander and others for reviewing ??
Example 3ā Assigning Values To Potentially Null Objects
FP Concepts Used: āApplicativeā
Use Case: Letās say we want to give discount to the user if the user is logged in and if we are running promotion (i.e. discount exists).

Letās say we are using the applyDiscount method below. As you can imagine, applyDiscount might throw null errors if either the user (the left-hand side or the discount (the right-hand side) is null.
//Adds discount to the user object if BOTH user and discount exists.//Throws null errors if either user or discount is nullconst applyDiscount = (user, discount) => { let userClone = clone(user);// use some lib to make a copy
**userClone.discount = discount.code;** return userClone;}
Letās see how we can solve this using āapplicativeā.
Applicative:
Any Class that have a method āapā and implements the Applicative spec is called an Applicative. Applicatives can be used in functions that are dealing with null values on both left-hand-side(user) and right-hand-side(discount) of the equation.
It turns out āMaybeā Monads (and every Monads) also implement āapā spec and hence are also āApplicativesā and not just Monads. So we can use āMaybeā Monads to deal with null at function level.
Letās see how we can solve make applyDiscount work using Maybe used as an āapplicativeā.
Step 1: wrap our potential null values in Maybe Monads
const maybeUser = Maybe(user);const maybeDiscount = Maybe(discount);
Step 2: Rewrite the function and curry it so we can pass one param at a time.
//Rewrite the function and curry it so we can//pass one param at a timevar applyDiscount = curry(function(user, discount) {
user.discount = discount.code;
return user;});
Step 3: letās pass the first argument(maybeUser) to applyDiscount via āmapā.
//pass the first argument to applyDiscount via "map"**const maybeApplyDiscountFunc = maybeUser.map(applyDiscount);**//Note, since applyDiscount is "curried", and "map" will only pass 1 parameter, the return result (**maybeApplyDiscountFunc**) will be a Maybe wrapped "applyDiscount" function that now has maybeUser(1st param) in it's closure.**In other words, we now have a function wrapped in a Monad!**
Step 4: Deal With maybeApplyDiscountFunc
At this stage maybeApplyDiscountFunc can be:
1. If user actually exists, then maybeApplyDiscountFunc is a function wrapped inside a Maybe.
2. If the user does not exist, then maybeApplyDiscountFunc will be āNothingā (subclass of Maybe)
If user doesnāt exist, then āNothingā is returned and any further interaction with this are ignore completely. So if we pass 2nd argument, nothing happens. And also no Null errors are thrown.
But in the case where the user actually exists, we can try to pass the 2nd argument to maybeApplyDiscountFunc via āmapā to execute the function like below:
maybeDiscount.map(maybeApplyDiscountFunc)! // PROBLEM!
Uh oh! āmapā doesnāt know how to run function(maybeApplyDiscountFunc) when the function itself is inside a MayBe!
Thatās why we need a different interface to deal with this scenario. It turns out thatās āapā!
Step5: Letās recap āapā function. āapā method takes another Maybe monad and passes/applies the function itās currently storing to that Maybe.
So we can simply apply (āapā) maybeApplyDiscountFunc to maybeDiscount instead of using āmapā like below and itāll work like a charm!
maybeApplyDiscountFunc.**ap**(maybeDiscount)//Internally it is doing the following because applyDiscount is store in the this.val of maybeApplyDiscountFunc wrapper:maybeDiscount.map(applyDiscount)//Now, if maybeDiscount actually has the discount, then the function is is run.If maybeDiscount is Null, then nothing happens.
FYI: Apparently there is a change in the FL spec, The old version has (eg):
Just(f).ap(Just(x))(wherefis a function andxis a value) but the new version would have you writeJust(x).ap(Just(f))But the implementations mostly havenāt changed yet. Thanks keithalexander
To summarize, if you have a function that deals with multiple parameters that might all be null, you curry it first, then put it inside a Maybe. Further, also put all params in a Maybe and then use āapā to run the function.
curryN function
We are familiar with ācurryā. It simply converts a function that takes multiple arguments to take them one-by-one.
**//Curry Example:**const add = (a, b) =>a+b;const curriedAdd = R.curry(add);const add10 = curriedAdd(10);//pass the 1st argument. Returns a function that takes 2nd (b) parameter.//run function by passing 2nd argumentadd10(2) // -> 12 //internally runs "add" with 10 and 2.
But instead of adding just two numbers, what if the add function can sum up all the numbers passed to it as an argument?
const add = (...args) => R.sum(args); //sum all the numbers in args
We can still curry it by limiting number of args using curryN like below:
**//curryN example**const add = (...args) => R.sum(args);//CurryN Example:const add = (...args) => R.sum(args);const add3Numbers = R.**curryN**(3, add);const add5Numbers = R.**curryN**(5, add);const add10Numbers = R.**curryN**(10, add);add3Numbers(1,2,3) // 6add3Numbers(1) // returns a function that takes 2 more params.add3Numbers(1, 2) // returns a function that take 1 more param.
Using ācurryNā to wait for number of function calls
Letās say we want to write a function that only logs if we call it 3 times (and ignore the 1st and 2nd call). Something like below:
//impurelet counter = 0;const logAfter3Calls = () => {
if(++counter == 3)
console.log('called me 3 times');}logAfter3Calls() // Nothing happenslogAfter3Calls() // Nothing happenslogAfter3Calls() // 'called me 3 times'
We can simulate that using curryN like below.
//Pureconst log = () => {
console.log('called me 3 times');}**const logAfter3Calls = R.curryN(3, log);**//call**logAfter3Calls('')('')('')**//'called me 3 times'//Note: We are passing '' to satisfy CurryN that we are passing some parameter.
Note: Weāll be using this technique in the Applicative validation.
Example 4ā Collecting And Displaying Multiple Errors
Topics covered: Validation (aka āValidation Functorā, āValidation Applicativeā, āValidation Monadā).
Validations are commonly referred as Validation Applicative because it is commonly used for validation using itās āapā(apply) function.
Validations are similar to Either Monads and used to work with composing multiple error-throwing functions. But unlike with Either Monad, where we typically use its āchainā method to compose, in Validation Monads, we typically use āapā method to compose. And unlike eitherās āchainā method, where we only collect the 1st error, āapā method, especially in Validation Monads allows us to collect all the errors in an Array.
They are typically used in form validation where we may want to show all the errors at the same time.
Use case: We have a sign up form that validates username, password and email using 3 functions(isUsernameValid, isPwdLengthCorrect and ieEmailValid. We need to show all 1, 2 or 3 errors if they all occur at the same time.
In order to show multiple errors, use āValidationā Functor
OK, letās see how to implement it using āValidation Applicativeā.
Weāll use data.validation lib from folktalejs because ramda-fantasy doesnāt implement it yet.
Similar to āEitherā Monad, it has two constructors: Success and Failure. These are like subclasses that each implement Eitherās specs.
Step1: In order to use Validation, all we need to do is to wrap valid values and errors inside Success and Failure constructors (i.e. create instances of those classes).
const Validation = require('data.validation') //from [folktalejs](https://github.com/folktale/data.validation)const Success = Validation.Successconst Failure = Validation.Failureconst R = require('ramda');**//Instead Of:**function isUsernameValid(a) {
return /^(0|[1-9][0-9]*)$/.test(a) ?
["Username can't be a number"] : a}**//Use:**function isUsernameValid(a) {
return /^(0|[1-9][0-9]*)$/.test(a) ?
**Failure**(["Username can't be a number"]) : **Success**(a)}
Repeat the process for ALL error throwing validation functions.
Step 2: Create a dummy function to hold validation success.
const returnSuccess = () => 'success';//simply returns success
Step 3: Use curryN to repeatedly apply āapā
The problem with āapā is that the left-hand side should be a functor (or a monad) containing function.
For example, letās say we want to repeatedly apply āapā like below. It will only work if monad1 contains a function. And the result of monad1.ap(monad2) i.e. resultingMonad is also a monad with a function so that we can āapā to monad3.
**let finalResult = monad1.ap(monad2).ap(monad3)**//Can be rewritten as:let resultingMonad = monad1.ap(monad2)let **finalResult** = resultingMonad.ap(monad3)**//will only work if: monad1 has a function and monad1.ap(monad2) results in another monad (resultingMonad) with a function**
Generally speaking, we need 2 monads that has functions in order to apply āapā twice.
In our case, we have 3 functions that we need to apply.
Letās say we did something like below.
Success(returnSuccess)
.ap(isUsernameValid(username)) //works
.ap(isPwdLengthCorrect(pwd))//wont work
.ap(ieEmailValid(email))//wont work
The above wonāt work because Success(returnSuccess).ap(isUsernameValid(username)) will result in a value. And we can no longer continue to do āapā on 2nd and 3rd function.
Enter curryN.
We can use curryN to keep returning function until it is called āNā number of times.
So we can simply do:
//3 coz we are calling "ap" 3 times.let success = R.curryN(3, returnSuccess);
Now, the curried success keeps returning function 3 times.
function validateForm(username, pwd, email) {
//3 coz we are calling "ap" 3 times.
let success = R.curryN(3, returnSuccess); return Success(success)// default; used for 3 "ap"s
.ap(isUsernameValid(username))
.ap(isPwdLengthCorrect(pwd))
.ap(ieEmailValid(email))}
Putting it all together:
If you liked the post by clicking on the ? it below and sharing it on Twitter! Thanks for reading! ??
My Other Posts
_LATEST: The Inner workings of the Browser ā for JavaScript & Web Developers _Use code: INNER15 and get 50% off!__
Functional Programming
- JavaScript Is Turing Complete ā Explained
- Functional Programming In JS ā With Practical Examples (Part 1)
- Functional Programming In JS ā With Practical Examples (Part 2)
ES6
WebPack
- Webpack ā The Confusing Parts
- Webpack & Hot Module Replacement [HMR] (under-the-hood)
- Webpackās HMR And React-Hot-Loader ā The Missing Manual
Draft.js
React And Redux :
- Step by Step Guide To Building React Redux Apps
- A Guide For Building A React Redux CRUD App (3-page app)
- Using Middlewares In React Redux Apps
- Adding A Robust Form Validation To React Redux Apps
- Securing React Redux Apps With JWT Tokens
- Handling Transactional Emails In React Redux Apps
- The Anatomy Of A React Redux App