DEV Community

Discussion on: Functional Programming - Pure Functions

Collapse
 
iquardt profile image
Iven Marquardt • Edited

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>"
Enter fullscreen mode Exit fullscreen mode

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

Collapse
 
pramila_15 profile image
Pramila Dalavai

This is great :)