FP for the practical programmer. pt1: The Either type.

Photo by Michal Matlon


FP is an abbreviation for functional programming. After having experienced OOP(object oriented programming) and FP, I am in favor of FP and believe that many people, once the ideas are understood, will feel the same.

  • higher order functions. You are using map, filter, reduce/fold on a daily basis? These are higher order functions.
  • lambda functions. Enjoy creating functions on the fly within your filter, map and reduce/fold? Yep, I do too.


  • Whenever something is written in italic I want to mimic the readers (yes, I am talking about you) possible thoughts and questions. Something like But how is this better than what I already now? or And how do I use this in my everyday code? to give two examples.
  • Whenever something is written in bold, I want to highlight something for the reader.


Either is a type that is used whenever you are doing something that can fail.

Idea of having a function returning an Either
Type definitions for the Either type. Function to create a value of type Left and Right.
Function that would blow up our application code.
[ERR]: "Executed JavaScript Failed:" [ERR]: Unexpected error occured!
Using Either instead of throwing an exception.
[LOG]: "I am alive! The result was: ",{"_tag": "Left", "left": {}}
Leveraging Either type
[LOG]: "We got an error! The error message was: ", "Unexpected error occured!" 
Just adapted the value from 1339 to 1338
[LOG]: “I am alive! The result was: “, 1348

Recap, what did we get out of this, so far?

  • Code that could break our application was replaced with code that returns a value of type Either.


Let’s see how we can turn any function that would blow up to leverage our new friend, the Either type! We create a function that we call “safeCall” which takes a function that could blow up our application and in turn, returns a function that returns the Either type instead! Just another higher order function, like your everyday map and filter, nothing scary.

Using safeCall to turn any unsafe function into a function that uses the Either type instead!
[LOG]: "Got an error! Error: ", "Unexpected error occured!"
Calling the function with 1338 instead of 1339.
[LOG]: "result: ", 1348



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Pierre Dahmani

Pierre Dahmani

Full Stack Software Engineer enjoying Typescript, React Native and Functional Programming.