The two fundamental operations in a monad are:

  1. unit (also called return or pure): wraps a value in the monad
  2. bind (also called flatMap or >>=): allows you to chain operations on monadic values

The case for monads

var log = ''; 
 
const f = x => { x + 10; log += 'added 10\n'; }; 
 
const g = y => y * 100; log += 'multiplied by 100\n'; }; 
 
const h = z => g(f(z)); 
 
const h2 = z => g(f(z)) + g(f(z));

Here the Global Variable log is updated each time f or g is called, i.e. these Functions produce a Side-effect. This means that f and g are NOT Pure. Looking at the Function, h2, we can see that we can’t simply evaluate g(f(z)) once and then double its Value like we can in a Purely Functional Language. These Functions need to be called again and again so that their Side-effects can occur. But we’re learning Functional Programming using PureScript, which is Pure. So, how do we implement this sort of Functionality in a Pure way using PureScript (or Haskell)?

f :: Int -> Tuple String Int 
f x = Tuple "added 10\n" (x + 10) 
 
g :: Int -> Tuple String Int 
g y = Tuple "multiplied by 100\n" (y + 100)