loading...

Functional Programming - Pure Functions

pramila_15 profile image Pramila Dalavai ・1 min read

Today we are gonna talk about pure functions, which is one of the core concepts of functional programming.No doubt pure functions make your life easier without affecting your application's state.
Rules for pure functions:

  1. The function should take in at least one argument.
  2. The function should return a value or another function.
  3. The function should not change or mutate any of its arguments. Impure functions example:
function Header(text) {
let h1 = document.createElement('h1');
h1.innerText = text;
document.body.appendChild(h1);
}
Header("Header() caused side effects");

In React, the UI is expressed with pure functions. In the following example, you can see the function doesn't mutate DOM. This function
will create a heading-one element, and it is up to some other part of the application to use that element to change the DOM:

const Header = (props) => <h1>{props.title}</h1>

Hence pure functions do not cause side effects, set global variables, or change anything about the application state.

Discussion

pic
Editor guide
Collapse
iquardt profile image
Iven Marquardt

In an impure language like Javascript you can render impure functions like Header pure by returning a description of the impure computation instead of running it. Then you can use functor to transform this description and monad to combine several descriptions:

const Header = text => () => {
  const h1 = document.createElement('h1');
  h1.innerText = text;
  document.body.appendChild(h1);
  return h1;
};

// Functor

const map = f => tx =>
  () => f(tx());

// Monad

const chain = mx => fm =>
  () => fm(mx()) ();

// MAIN

const data = Header("foo");

const foo = map(
  h1 => (h1.innerText = h1.innerText.toUpperCase(), h1))
    (data);

const bar = chain(
  foo) (h1 =>
    () => (h1.innerText += "bar", h1));

// no DOM update yet

bar(); // updates the DOM with "<h1>FOObar</h1>"

This way you can separate the pure realm of your program from the impure one.

Collapse
pramila_15 profile image
Pramila Dalavai Author

This is great :)