SlideShare a Scribd company logo
1 of 79
Download to read offline
FUNCTIONAL PROGRAMMING
for OO programmers (Part 2)
WHAT
• Pure versus Impure (exercise)
• Currying (exercise)
• Map, Filter, Reduce (exercise)
• Functors,Applicative Functors, Monads (exercise)
are we diving into?
PURE OR IMPURE
recognize pure functions
RECOGNIZE
• Functions that don’t change anything out-of-scope
and don’t depend on anything out-of-scope are
called “pure”
• A pure function always gives the same result given
the same parameters; independent of program/
system state
pure functions
RECOGNIZE
pure function
var	
  values	
  =	
  {	
  a:	
  1	
  };	
  
function	
  pureFunction	
  (a)	
  {	
  
	
  	
  var	
  b	
  =	
  1;	
  
	
  	
  a	
  =	
  a	
  *	
  b	
  +	
  2;	
  
	
  	
  return	
  a;	
  
}	
  
RECOGNIZE
impure function
var	
  values	
  =	
  {	
  a:	
  1	
  };	
  
function	
  impureFunction	
  (items)	
  {	
  
	
  	
  var	
  b	
  =	
  1;	
  
	
  	
  items.a	
  =	
  items.a	
  *	
  b	
  +	
  2;	
  
	
  	
  return	
  items;	
  
}	
  
LET’S PLAY
pure or impure?
PURE OR IMPURE?
function	
  getQueryVariable(variable)	
  {	
  
	
  	
  var	
  query	
  =	
  window.location.search.substring(1);	
  
	
  	
  var	
  vars	
  =	
  query.split('&');	
  
	
  	
  for	
  (var	
  i	
  =	
  0;	
  i	
  <	
  vars.length;	
  i++)	
  {	
  
	
  	
  	
  	
  	
  	
  var	
  pair	
  =	
  vars[i].split('=');	
  
	
  	
  	
  	
  	
  	
  if	
  (decodeURIComponent(pair[0])	
  ===	
  variable)	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  return	
  decodeURIComponent(pair[1]);	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  }	
  
	
  	
  	
  	
  }	
  
}
PURE OR IMPURE?
function	
  random(mZ,	
  mW)	
  {	
  
	
  	
  mZ	
  =	
  36969	
  *	
  (mZ	
  &	
  65535)	
  +	
  (mZ	
  >>	
  16);	
  
	
  	
  mW	
  =	
  18000	
  *	
  (mW	
  &	
  65535)	
  +	
  (mW	
  >>	
  16);	
  
	
  	
  return	
  (mZ	
  >>	
  16)	
  +	
  mW;	
  
}	
  
PURE OR IMPURE?
function	
  addAndShow(a,	
  b,	
  console)	
  {	
  
	
  	
  var	
  c	
  =	
  a	
  +	
  b;	
  
	
  	
  console.log(a,	
  '	
  +	
  ',	
  b,	
  '	
  =	
  ',	
  c);	
  
	
  	
  return	
  c;	
  
};	
  
PURE OR IMPURE?
var	
  number	
  =	
  1;	
  
var	
  increment	
  =	
  function()	
  {	
  
	
  	
  return	
  number	
  +=	
  1;	
  
};	
  
increment();	
  
PURE OR IMPURE?
var	
  number	
  =	
  1;	
  
var	
  incrementAlt	
  =	
  function(n)	
  {	
  
	
  	
  	
  	
  return	
  n	
  +	
  1;	
  
};	
  
incrementAlt(number);
CURRYING
first-order function and higher-order function capabilities
CURRYING
var	
  people	
  =	
  [	
  
	
  	
  {	
  name:	
  'Calvin'	
  },	
  
	
  	
  {	
  name:	
  'John'	
  },	
  
	
  	
  {	
  name:	
  'Thomas'	
  }	
  
];	
  
//	
  function	
  with	
  hardcoded	
  key	
  'name'	
  to	
  retrieve	
  list	
  of	
  names	
  
function	
  getPersonName(obj)	
  {	
  
	
  	
  return	
  obj['name'];	
  
}	
  
//	
  mapping	
  to	
  the	
  hardcoded	
  function	
  
var	
  names	
  =	
  people.map(getPersonName);	
  
console.log(names);
JavaScript
CURRYING
//	
  Specify	
  the	
  key	
  on-­‐the-­‐fly	
  by	
  using	
  a	
  generic	
  function.	
  
function	
  getByKey(key,	
  obj)	
  {	
  
	
  	
  return	
  function(obj)	
  {	
  
	
  	
  	
  	
  return	
  obj[key];	
  
	
  	
  };	
  
}	
  
JavaScript
CURRYING
function	
  getByKey(key,	
  obj)	
  {	
  
	
  	
  return	
  function(obj)	
  {	
  
	
  	
  	
  	
  return	
  obj[key];	
  
	
  	
  };	
  
}	
  
var	
  getByKeyPartial	
  =	
  getByKey('name');	
  
console.log(getByKeyPartial);	
  
var	
  names2	
  =	
  people.map(getByKeyPartial);	
  
console.log(names2);	
  
[Function]
curried function or partial function
JavaScript
CURRYING
function	
  getByKey(key,	
  obj)	
  {	
  
	
  	
  return	
  function(obj)	
  {	
  
	
  	
  	
  	
  return	
  obj[key];	
  
	
  	
  };	
  
}	
  
var	
  names3	
  =	
  people.map(getByKey('name'));	
  
console.log(names3);
[Function]
curried function or partial function
equivalent to:
getByKey(‘name’)(obj) in this context
JavaScript
CURRYING
module	
  Main	
  where	
  
f	
  ::	
  Integer	
  
f	
  =	
  max	
  4	
  5	
  
fPartial	
  ::	
  (Ord	
  a,	
  Num	
  a)	
  =>	
  a	
  -­‐>	
  a	
  	
  
fPartial	
  =	
  max	
  4	
  
main	
  ::	
  	
  IO	
  ()	
  
main	
  =	
  do	
  
	
  	
  print	
  f	
  	
  
	
  	
  let	
  g	
  =	
  fPartial	
  10	
  
	
  	
  print	
  g
Haskell
CURRYING
people	
  ::	
  	
  [(String,	
  String)]	
  
people	
  =	
  [("name",	
  "Calvin")	
  
	
  	
  	
  	
  ,("wat",	
  "John")	
  
	
  	
  	
  	
  ,("name",	
  "Thomas")	
  
	
  	
  	
  	
  ]	
  
Haskell
CURRYING
{-­‐	
  generic	
  filterByKey	
  function	
  that	
  accepts	
  a	
  string	
  as	
  
keyname	
  and	
  the	
  data	
  structure	
  shown	
  previously	
  -­‐}	
  
filterByKey	
  ::	
  Eq	
  a	
  =>	
  a	
  -­‐>	
  [(a,	
  t)]	
  -­‐>	
  [t]	
  
filterByKey	
  _	
  []	
  =	
  []	
  
filterByKey	
  p	
  ((k,	
  v):xs)	
  
	
  	
  	
  	
  |	
  p	
  ==	
  k	
  	
  	
  	
  =	
  v	
  :	
  filterByKey	
  p	
  xs	
  
	
  	
  	
  	
  |	
  otherwise	
  =	
  filterByKey	
  p	
  xs	
  
filterByName	
  ::	
  [(String,	
  t)]	
  -­‐>	
  [t]	
  
filterByName	
  =	
  filterByKey	
  "name"
Haskell
[Function]
curried function or partial function
CURRYING
main	
  ::	
  	
  IO	
  ()	
  
main	
  =	
  do	
  
	
  	
  	
  	
  let	
  names2	
  =	
  filterByKey	
  "name"	
  people	
  
	
  	
  	
  	
  print	
  names2	
  
	
  	
  	
  	
  let	
  names3	
  =	
  filterByName	
  people	
  
	
  	
  	
  	
  print	
  names3	
  
Haskell
[Function]
curried function or partial function
MAP, FILTER, REDUCE
Look ma, no loops
MAP, FILTER, REDUCE
//	
  map,	
  reduce	
  and	
  filter	
  are	
  built-­‐in	
  as	
  methods	
  of	
  the	
  	
  
//	
  Array	
  class	
  in	
  JS	
  
var	
  aList	
  =	
  [0,	
  1,	
  2];	
  
var	
  newList	
  =	
  aList.map(function	
  (i)	
  {	
  
	
  	
  return	
  i	
  +	
  1;	
  
});	
  
console.log(newList);	
  
console.log(aList);
JavaScript map
MAP, FILTER, REDUCE
aList	
  ::	
  	
  [Integer]	
  
aList	
  =	
  [0,	
  1,	
  2]	
  
addOne	
  ::	
  [Integer]	
  
addOne	
  =	
  map	
  (+1)	
  aList	
  
Haskell map
MAP, FILTER, REDUCE
//	
  map,	
  reduce	
  and	
  filter	
  are	
  built-­‐in	
  as	
  methods	
  of	
  the	
  	
  
//	
  Array	
  class	
  in	
  JS	
  
var	
  aList	
  =	
  [0,	
  1,	
  2];	
  
var	
  lessThanTwo	
  =	
  aList.filter(function	
  (i)	
  {	
  
	
  	
  return	
  i	
  <	
  2;	
  
});	
  
console.log(lessThanTwo);	
  
console.log(aList);
JavaScript filter
MAP, FILTER, REDUCE
aList	
  ::	
  	
  [Integer]	
  
aList	
  =	
  [0,	
  1,	
  2]	
  
lessThanTwo	
  ::	
  [Integer]	
  
lessThanTwo	
  =	
  filter	
  (<2)	
  aList	
  
Haskell filter
MAP, FILTER, REDUCE
//	
  map,	
  reduce	
  and	
  filter	
  are	
  built-­‐in	
  as	
  methods	
  of	
  the	
  	
  
//	
  Array	
  class	
  in	
  JS	
  
var	
  aList	
  =	
  [0,	
  1,	
  2];	
  
var	
  reduceToSum	
  =	
  aList.reduce(function	
  (a,	
  b)	
  {	
  
	
  	
  return	
  a	
  +	
  b;	
  
});	
  
console.log(reduceToSum);	
  
console.log(aList);	
  
reduce
MAP, FILTER, REDUCE
aList	
  ::	
  	
  [Integer]	
  
aList	
  =	
  [0,	
  1,	
  2]	
  
reduceToSum	
  ::	
  Integer	
  
reduceToSum	
  =	
  foldl	
  (+)	
  0	
  aList	
  
Haskell reduce (foldl and foldr)
FUNCTORS
a function that, given a value and a function, does the right thing
FUNCTORS
function	
  addOne(value)	
  {	
  
	
  	
  return	
  value	
  +	
  1;	
  
}	
  
console.log(addOne(10));	
  	
  //	
  11	
  
function	
  addTwo(value)	
  {	
  
	
  	
  return	
  value	
  +	
  2;	
  
}	
  
console.log(addTwo(10));	
  	
  //	
  12	
  
JavaScript
FUNCTORS
//	
  A	
  not-­‐quite-­‐there	
  Functor	
  
function	
  aFunctor(value,	
  fn)	
  {	
  
	
  	
  return	
  fn(value);	
  
}	
  
console.log(aFunctor(10,	
  addOne));	
  //	
  11,	
  works	
  as	
  expected	
  
console.log(aFunctor([1,	
  2,	
  3],	
  addOne));	
  	
  //	
  '1,2,31'	
  is	
  
returned,	
  which	
  is	
  not	
  what	
  we	
  want	
  
JavaScript
FUNCTORS
function	
  betterFunctor(value,	
  fn)	
  {	
  
	
  	
  if	
  (typeof	
  value	
  ===	
  'number')	
  {	
  
	
  	
  	
  	
  return	
  fn(value);	
  	
  
	
  	
  }	
  else	
  {	
  
	
  	
  	
  	
  var	
  map	
  =	
  Array.prototype.map;	
  
	
  	
  	
  	
  return	
  map.call(value,	
  fn);	
  
	
  	
  }	
  
}	
  
JavaScript
FUNCTORS
console.log(betterFunctor([1,	
  2,	
  3],	
  addOne));	
  	
  //	
  [2,	
  3,	
  
4]	
  is	
  what	
  we	
  expected	
  
console.log(betterFunctor(10,	
  addOne));	
  	
  	
  	
  	
  	
  	
  	
  	
  //	
  11	
  is	
  
what	
  we	
  expected	
  
JavaScript
FUNCTORS
//	
  JavaScript's	
  Array's	
  map	
  method	
  is	
  a	
  functor!	
  :-­‐)	
  
var	
  map	
  =	
  Array.prototype.map;	
  
console.log(map.call([1,	
  2,	
  3],	
  addOne));	
  	
  	
  	
  	
  	
  	
  //	
  [2,	
  3,	
  
4]	
  is	
  what	
  we	
  expected.	
  	
  
console.log([].map.call([1,	
  2,	
  3],	
  addOne));	
  	
  	
  	
  //	
  This	
  
works	
  too	
  
JavaScript
FUNCTORS
addOne	
  ::	
  	
  Num	
  a	
  =>	
  a	
  -­‐>	
  a	
  
addOne	
  a	
  =	
  a	
  +	
  1	
  
addTwo	
  ::	
  	
  Num	
  a	
  =>	
  a	
  -­‐>	
  a	
  
addTwo	
  a	
  =	
  a	
  +	
  2	
  
result	
  ::	
  	
  Num	
  b	
  =>	
  [b]	
  -­‐>	
  [b]	
  
result	
  xs	
  =	
  	
  map	
  addOne	
  xs	
  
Haskell
COMPARISON
Functors vs Applicative Functors vs Monads
Functors Applicatives Monads
example
(+3) [2]
== [5]
Just(+3)
<*>
Just 2
== Just 5
Just 4
>>=
makeHalf
== Just 2
examples
functions
map, fmap, <*> <*>, <$>, liftA2 >>=, liftM
brings function
operator in
execute operationgeneralized
map
does both <*> & <$>
apply fn to
wrapped value
apply wrapped fn to
wrapped value
apply fn that returns
a wrapped value
to a wrapped value
MAYBE FUNCTORS
an often-used functor; and more about functors
MAYBE FUNCTORS
• Captures null check
• Value inside may or may not be there
• Maybe has two subclasses - ‘Just’ or ‘Nothing’ (Haskell)
• Also referred to as Option with subclasses ‘Some’ or
‘None’ (Scala)
• Also available in Swift, e.g. Optional, enum Either<NSError,
User>
MAYBE FUNCTORS
var	
  aList	
  =	
  [1,	
  2,	
  3];	
  
function	
  compose(f,	
  g)	
  {	
  
	
  	
  return	
  function	
  (x)	
  {	
  
	
  	
  	
  	
  return	
  f(g(x));	
  
	
  	
  };	
  
}	
  
function	
  addOne(value)	
  {	
  
	
  	
  return	
  value	
  +	
  1;	
  
}	
  
function	
  addTwo(value)	
  {	
  
	
  	
  return	
  value	
  +	
  2;	
  
}
JavaScript
MAYBE FUNCTORS
console.log(aList.map(compose(addOne,	
  addTwo)));	
  
console.log(aList.map(addTwo).map(addOne));	
  
function	
  mayBe(value,	
  fn)	
  {	
  
	
  	
  return	
  value	
  ===	
  null	
  ||	
  value	
  ===	
  undefined	
  ?	
  value	
  :	
  
fn(value);	
  
}	
  
JavaScript
MAYBE FUNCTORS
console.log(mayBe(undefined,	
  compose(addOne,	
  addTwo)));	
  	
  	
  	
  	
  
//	
  returns	
  expected	
  result	
  undefined	
  
console.log(mayBe(mayBe(undefined,	
  addTwo),	
  addOne));	
  	
  	
  	
  	
  	
  	
  
//	
  returns	
  expected	
  result	
  undefined	
  
console.log(mayBe(1,	
  compose(addOne,	
  addTwo)));	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  
//	
  returns	
  expected	
  result	
  4	
  	
  
console.log(mayBe(mayBe(1,	
  addTwo),	
  addOne));	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  
//	
  returns	
  expected	
  result	
  4	
  
JavaScript
MAYBE FUNCTORS
addOne	
  ::	
  	
  Num	
  a	
  =>	
  a	
  -­‐>	
  a	
  
addOne	
  a	
  =	
  a	
  +	
  1	
  
addTwo	
  ::	
  	
  Num	
  a	
  =>	
  a	
  -­‐>	
  a	
  
addTwo	
  a	
  =	
  a	
  +	
  2	
  
composedFn	
  ::	
  	
  Integer	
  -­‐>	
  Integer	
  
composedFn	
  =	
  addOne	
  .	
  addTwo	
  
res	
  ::	
  	
  [Integer]	
  
res	
  =	
  map	
  composedFn	
  aList
Haskell
MAYBE FUNCTORS
main	
  ::	
  	
  IO	
  ()	
  
main	
  =	
  do	
  
	
  	
  	
  	
  print	
  res	
  
	
  	
  	
  	
  let	
  res2	
  =	
  fmap	
  composedFn	
  Nothing	
  
	
  	
  	
  	
  print	
  res2	
  
	
  	
  	
  	
  let	
  res3	
  =	
  fmap	
  composedFn	
  (Just	
  1)	
  
	
  	
  	
  	
  print	
  res3
Haskell
APPLICATIVES
apply wrapped function to wrapped value
APPLICATIVES
var	
  none	
  =	
  {	
  
	
  	
  	
  	
  map:	
  function()	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  return	
  none;	
  
	
  	
  	
  	
  },	
  
	
  	
  	
  	
  bind:	
  function()	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  return	
  none;	
  
	
  	
  	
  	
  },	
  
	
  	
  	
  	
  	
  
	
  	
  	
  	
  toString:	
  function()	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  return	
  'none';	
  
	
  	
  	
  	
  }	
  
};
JavaScript
APPLICATIVES
function	
  some(value)	
  {	
  
	
  	
  	
  	
  return	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  map:	
  function(func)	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  return	
  some(func(value));	
  
	
  	
  	
  	
  	
  	
  	
  	
  },	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  
	
  	
  	
  	
  	
  	
  	
  	
  bind:	
  function(func)	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  return	
  func(value);	
  
	
  	
  	
  	
  	
  	
  	
  	
  },	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  
	
  	
  	
  	
  	
  	
  	
  	
  toString:	
  function()	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  return	
  "some("	
  +	
  value	
  +	
  ")";	
  
	
  	
  	
  	
  	
  	
  	
  	
  }	
  
	
  	
  	
  	
  };	
  
}	
  
JavaScript
APPLICATIVES
var	
  functor	
  =	
  {	
  
	
  	
  	
  	
  map:	
  function(func,	
  option)	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  return	
  option.map(func);	
  
	
  	
  	
  	
  },	
  
	
  	
  	
  	
  unit:	
  some,	
  
	
  	
  	
  	
  applyFunctor:	
  function(funcOption,	
  argOption)	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  return	
  funcOption.bind(function(func)	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  return	
  argOption.map(func);	
  
	
  	
  	
  	
  	
  	
  	
  	
  });	
  
	
  	
  	
  	
  }	
  
};
JavaScript
APPLICATIVES
function	
  curry(func,	
  numberOfArguments)	
  {	
  
	
  	
  return	
  function(value)	
  {	
  
	
  	
  	
  	
  if	
  (numberOfArguments	
  ===	
  1)	
  {	
  
	
  	
  	
  	
  	
  	
  return	
  func(value);	
  
	
  	
  	
  	
  }	
  else	
  {	
  
	
  	
  	
  	
  	
  	
  return	
  curry(func.bind(null,	
  value),	
  numberOfArguments	
  -­‐	
  1);	
  
	
  	
  	
  	
  }	
  
	
  	
  };	
  
}
JavaScript
APPLICATIVES
//	
  Usage	
  
var	
  four	
  =	
  some(4);	
  
var	
  six	
  =	
  some(6);	
  
console.log(four.toString());	
  
console.log(six.toString());	
  
function	
  add(a,	
  b)	
  {	
  
	
  	
  return	
  a	
  +	
  b;	
  
}	
  
var	
  result	
  =	
  functor.applyFunctor(functor.map(curry(add,	
  2),	
  four),	
  six);	
  
console.log(result.toString());	
  //	
  some(10)
JavaScript
APPLICATIVES
result	
  =	
  functor.applyFunctor(functor.map(curry(add,	
  2),	
  
none),	
  six);	
  
console.log(result.toString());	
  
result	
  =	
  functor.applyFunctor(functor.map(curry(add,	
  2),	
  
four),	
  none);	
  
console.log(result.toString());
JavaScript
APPLICATIVES
//	
  A	
  cleaner	
  API	
  for	
  our	
  applicative	
  functor	
  operations	
  
functor.applyFunctorUncurried	
  =	
  function(func)	
  {	
  
	
  	
  var	
  args	
  =	
  Array.prototype.slice.call(arguments,	
  1);	
  
	
  	
  return	
  args.reduce(	
  
	
  	
  	
  	
  functor.applyFunctor,	
  
	
  	
  	
  	
  functor.unit(curry(func,	
  args.length))	
  
	
  	
  );	
  
};	
  
JavaScript
APPLICATIVES
var	
  result2	
  =	
  functor.applyFunctorUncurried(add,	
  four,	
  six);	
  
console.log(result2.toString());	
  
result2	
  =	
  functor.applyFunctorUncurried(add,	
  none,	
  six);	
  
console.log(result2.toString());	
  
result2	
  =	
  functor.applyFunctorUncurried(add,	
  four,	
  none);	
  
console.log(result2.toString());	
  
JavaScript
APPLICATIVES
import	
  Control.Applicative	
  
ans	
  ::	
  	
  Maybe	
  Integer	
  
ans	
  =	
  (+)	
  <$>	
  Just	
  4	
  <*>	
  Just	
  6	
  
main	
  ::	
  	
  IO	
  ()	
  
main	
  =	
  print	
  ans	
  
Haskell
MONADS
apply function that returns wrapped value to a wrapped value
MONAD
“A monad is just a monoid in the category of
endofunctors, what's the problem?”
- James Iry (Brief, Incomplete and Mostly Wrong
History of Programming Languages)
MONAD
Let’s
• understand the why,
• then, illustrate the how
• and, we will know what a monad is.
MONAD
Why?
avoid mutable state while chaining a group of
functions together (or executing a sequence of logic)
MONAD
mutation:
functions in imperative languages change the state of
values as logic is executed
MONAD
So what’s the big deal?
When data is mutable, parallel thread execution of your code on
multiple CPUs leads to race conditions
Can’t do parallel thread execution on your multi-core machine
idle resource
If we insist on parallel thread execution without locks
unpredictable results, i.e. errors
MONAD
MONAD
f (x)
x = g(x)
x = h(x)
x = i(x)
return x
MONAD
f (x)
x = g(x)
x = h(x)
x = i(x)
return x
x = 3
x = 5
x = 10
x = -3
x = -3
f (x)
x = g(x)
x = h(x)
x = i(x)
return x
f (x)
x = g(x)
x = h(x)
x = i(x)
return x
MONAD
x = 3
x = 5
x = 17
x = 4 x = -9
x = 7
x = 12
CPU #1 CPU #2
x = 4 x = -9
Shared
Memory, x
MONAD
As you can see, the same function results in indeterminate
results depending on the whims of the parallel OS-
controlled POSIX threads (“pthreads”)
We expect that when we write the code (“computation
logic”) for f(x), when given x = 3, f(x) will always result in
-3 but because x is mutable in traditional languages, this is
not the case if we try to make our program run on
multiple CPUs.
MONAD
Imperative languages that we are familiar with solve
this problem with
• locks (semaphores) on POSIX threads; or
• green threads (concurrent threads) and
asynchronous I/O
MONAD
Haskell has everything + more performant approaches:
• sparks (super-duper lightweight green threads)
• green threads
• semaphores
• immutable variables by default,“side effects” (mutability)
achieved via monads
f (x)
x1 = g(x)
x2 = h(x1)
x3 = i(x2)
return x3
f (x)
x1 = g(x)
x2 = h(x1)
x3 = i(x2)
return x3
MONAD
x = 3
x1 = 5
x2 = 10
x3 = -3 x3 = -3
x1 = 5
x2 = 10
CPU #1 CPU #2
x3 = -3 x3 = -3
MONAD
Haskell
f :: Num a => a -> a
f x = let
x1 = x + 2
x2 = x1 + 5
x3 = x2 - 13
in x3
f :: Num a => a -> a
f x = let
x = x + 2
x = x + 5
x = x - 13
in x
error:
variables in haskell
are immutable values!
no side effects!
MONAD
So, now, we know the Why?
avoid mutable state while chaining a group of
functions together (or executing a sequence of logic)
So, how can a monad achieve the magic illustrated in
the previous 2 slides?
MONAD
How?
• type container
• return
• bind
MONAD
var	
  Maybe	
  =	
  function(value)	
  {	
  //	
  container	
  
	
  	
  this.value	
  =	
  value;	
  
};	
  
Maybe.prototype.ret	
  =	
  function()	
  {	
  	
  //	
  return	
  
	
  	
  return	
  this.value;	
  
};	
  
Maybe.prototype.bind	
  =	
  function(func)	
  {	
  	
  //	
  bind	
  
	
  	
  if	
  (this.value	
  !==	
  null)	
  {	
  
	
  	
  	
  	
  return	
  func(this.value);	
  
	
  	
  }	
  
	
  	
  return	
  this.value;	
  
};
JavaScript
MONAD
//	
  lift:	
  takes	
  in	
  a	
  function	
  that	
  returns	
  a	
  normal	
  value	
  and	
  changes	
  it	
  in	
  a	
  monad	
  
Maybe.lift	
  =	
  function(func)	
  {	
  
	
  	
  return	
  function(value)	
  {	
  
	
  	
  	
  	
  return	
  new	
  Maybe(func(value));	
  
	
  	
  };	
  
};	
  
//	
  Usage	
  
var	
  addOne	
  =	
  function(value)	
  {	
  
	
  	
  return	
  value	
  +	
  1;	
  
};	
  
//	
  we	
  can	
  use	
  this	
  with	
  bind	
  
var	
  maybeAddOne	
  =	
  Maybe.lift(addOne);
JavaScript
MONAD
//	
  lift2	
  use	
  closures	
  to	
  get	
  values	
  from	
  the	
  two	
  monads	
  	
  
//	
  before	
  running	
  it	
  through	
  function,	
  handling	
  the	
  undefined	
  cases	
  
Maybe.lift2	
  =	
  function(func)	
  {	
  
	
  	
  return	
  function(M1,	
  M2)	
  {	
  
	
  	
  	
  	
  return	
  new	
  Maybe(M1.bind(function(value1){	
  
	
  	
  	
  	
  	
  	
  return	
  M2.bind(function(value2)	
  {	
  
	
  	
  	
  	
  	
  	
  	
  	
  return	
  func(value1,	
  value2);	
  
	
  	
  	
  	
  	
  	
  });	
  
	
  	
  	
  	
  }));	
  
	
  	
  };	
  
};
JavaScript
MONAD
var	
  add	
  =	
  function(a,	
  b)	
  {return	
  a	
  +	
  b;};	
  
var	
  m1	
  =	
  new	
  Maybe(1);	
  
var	
  m2	
  =	
  new	
  Maybe(2);	
  
var	
  m3	
  =	
  new	
  Maybe(undefined);	
  
var	
  liftM2Add	
  =	
  Maybe.lift2(add);	
  
liftM2Add(m1,	
  m2).ret();	
  //3	
  
liftM2Add(m3,	
  m2).ret();	
  //undefined	
  
liftM2Add(m1,	
  m3).ret();	
  //undefined	
  
JavaScript
MONAD
a	
  ::	
  	
  Maybe	
  Integer	
  
a	
  =	
  Just	
  1	
  
f	
  ::	
  	
  Integer	
  -­‐>	
  Maybe	
  Integer	
  
f	
  =	
  x	
  -­‐>	
  Just	
  (x	
  +	
  1)	
  
main	
  ::	
  	
  IO	
  ()	
  
main	
  =	
  do	
  
	
  	
  let	
  ans	
  =	
  a	
  >>=	
  f	
  
	
  	
  print	
  ans	
  	
  {-­‐	
  we	
  expect	
  to	
  get	
  Just	
  2	
  -­‐}
Haskell
MONAD
• type container
• return
• bind
• We pass in function(s) to operate values inside it
• and get a returned value
MONAD
The code
• http://github.com/calvinchengx/learnhaskell
THANKYOU
@calvinchengx
calvin.cheng.lc
calvinchengx
calvinx.com
CRAFTSMANSHIP
Master your craft - Procedural, OO, Functional

More Related Content

What's hot

The underestimated power of KeyPaths
The underestimated power of KeyPathsThe underestimated power of KeyPaths
The underestimated power of KeyPathsVincent Pradeilles
 
The Ring programming language version 1.5.1 book - Part 32 of 180
The Ring programming language version 1.5.1 book - Part 32 of 180The Ring programming language version 1.5.1 book - Part 32 of 180
The Ring programming language version 1.5.1 book - Part 32 of 180Mahmoud Samir Fayed
 
The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...
The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...
The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...John De Goes
 
The Death of Final Tagless
The Death of Final TaglessThe Death of Final Tagless
The Death of Final TaglessJohn De Goes
 
7 Habits For a More Functional Swift
7 Habits For a More Functional Swift7 Habits For a More Functional Swift
7 Habits For a More Functional SwiftJason Larsen
 
Functional Programming in Javascript - IL Tech Talks week
Functional Programming in Javascript - IL Tech Talks weekFunctional Programming in Javascript - IL Tech Talks week
Functional Programming in Javascript - IL Tech Talks weekyoavrubin
 
TDC218SP | Trilha Kotlin - DSLs in a Kotlin Way
TDC218SP | Trilha Kotlin - DSLs in a Kotlin WayTDC218SP | Trilha Kotlin - DSLs in a Kotlin Way
TDC218SP | Trilha Kotlin - DSLs in a Kotlin Waytdc-globalcode
 
The Ring programming language version 1.3 book - Part 25 of 88
The Ring programming language version 1.3 book - Part 25 of 88The Ring programming language version 1.3 book - Part 25 of 88
The Ring programming language version 1.3 book - Part 25 of 88Mahmoud Samir Fayed
 
Atomically { Delete Your Actors }
Atomically { Delete Your Actors }Atomically { Delete Your Actors }
Atomically { Delete Your Actors }John De Goes
 
The Ring programming language version 1.5.4 book - Part 22 of 185
The Ring programming language version 1.5.4 book - Part 22 of 185The Ring programming language version 1.5.4 book - Part 22 of 185
The Ring programming language version 1.5.4 book - Part 22 of 185Mahmoud Samir Fayed
 
Martin Fowler's Refactoring Techniques Quick Reference
Martin Fowler's Refactoring Techniques Quick ReferenceMartin Fowler's Refactoring Techniques Quick Reference
Martin Fowler's Refactoring Techniques Quick ReferenceSeung-Bum Lee
 
JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...
JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...
JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...PROIDEA
 
The Ring programming language version 1.5.2 book - Part 31 of 181
The Ring programming language version 1.5.2 book - Part 31 of 181The Ring programming language version 1.5.2 book - Part 31 of 181
The Ring programming language version 1.5.2 book - Part 31 of 181Mahmoud Samir Fayed
 
Functional programming in JavaScript
Functional programming in JavaScriptFunctional programming in JavaScript
Functional programming in JavaScriptJoseph Smith
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойSigma Software
 
Ramda, a functional JavaScript library
Ramda, a functional JavaScript libraryRamda, a functional JavaScript library
Ramda, a functional JavaScript libraryDerek Willian Stavis
 
The Ring programming language version 1.5.3 book - Part 34 of 184
The Ring programming language version 1.5.3 book - Part 34 of 184The Ring programming language version 1.5.3 book - Part 34 of 184
The Ring programming language version 1.5.3 book - Part 34 of 184Mahmoud Samir Fayed
 
Side by Side - Scala and Java Adaptations of Martin Fowler’s Javascript Refac...
Side by Side - Scala and Java Adaptations of Martin Fowler’s Javascript Refac...Side by Side - Scala and Java Adaptations of Martin Fowler’s Javascript Refac...
Side by Side - Scala and Java Adaptations of Martin Fowler’s Javascript Refac...Philip Schwarz
 
Ramda lets write declarative js
Ramda   lets write declarative jsRamda   lets write declarative js
Ramda lets write declarative jsPivorak MeetUp
 

What's hot (20)

Fp java8
Fp java8Fp java8
Fp java8
 
The underestimated power of KeyPaths
The underestimated power of KeyPathsThe underestimated power of KeyPaths
The underestimated power of KeyPaths
 
The Ring programming language version 1.5.1 book - Part 32 of 180
The Ring programming language version 1.5.1 book - Part 32 of 180The Ring programming language version 1.5.1 book - Part 32 of 180
The Ring programming language version 1.5.1 book - Part 32 of 180
 
The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...
The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...
The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...
 
The Death of Final Tagless
The Death of Final TaglessThe Death of Final Tagless
The Death of Final Tagless
 
7 Habits For a More Functional Swift
7 Habits For a More Functional Swift7 Habits For a More Functional Swift
7 Habits For a More Functional Swift
 
Functional Programming in Javascript - IL Tech Talks week
Functional Programming in Javascript - IL Tech Talks weekFunctional Programming in Javascript - IL Tech Talks week
Functional Programming in Javascript - IL Tech Talks week
 
TDC218SP | Trilha Kotlin - DSLs in a Kotlin Way
TDC218SP | Trilha Kotlin - DSLs in a Kotlin WayTDC218SP | Trilha Kotlin - DSLs in a Kotlin Way
TDC218SP | Trilha Kotlin - DSLs in a Kotlin Way
 
The Ring programming language version 1.3 book - Part 25 of 88
The Ring programming language version 1.3 book - Part 25 of 88The Ring programming language version 1.3 book - Part 25 of 88
The Ring programming language version 1.3 book - Part 25 of 88
 
Atomically { Delete Your Actors }
Atomically { Delete Your Actors }Atomically { Delete Your Actors }
Atomically { Delete Your Actors }
 
The Ring programming language version 1.5.4 book - Part 22 of 185
The Ring programming language version 1.5.4 book - Part 22 of 185The Ring programming language version 1.5.4 book - Part 22 of 185
The Ring programming language version 1.5.4 book - Part 22 of 185
 
Martin Fowler's Refactoring Techniques Quick Reference
Martin Fowler's Refactoring Techniques Quick ReferenceMartin Fowler's Refactoring Techniques Quick Reference
Martin Fowler's Refactoring Techniques Quick Reference
 
JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...
JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...
JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...
 
The Ring programming language version 1.5.2 book - Part 31 of 181
The Ring programming language version 1.5.2 book - Part 31 of 181The Ring programming language version 1.5.2 book - Part 31 of 181
The Ring programming language version 1.5.2 book - Part 31 of 181
 
Functional programming in JavaScript
Functional programming in JavaScriptFunctional programming in JavaScript
Functional programming in JavaScript
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай Мозговой
 
Ramda, a functional JavaScript library
Ramda, a functional JavaScript libraryRamda, a functional JavaScript library
Ramda, a functional JavaScript library
 
The Ring programming language version 1.5.3 book - Part 34 of 184
The Ring programming language version 1.5.3 book - Part 34 of 184The Ring programming language version 1.5.3 book - Part 34 of 184
The Ring programming language version 1.5.3 book - Part 34 of 184
 
Side by Side - Scala and Java Adaptations of Martin Fowler’s Javascript Refac...
Side by Side - Scala and Java Adaptations of Martin Fowler’s Javascript Refac...Side by Side - Scala and Java Adaptations of Martin Fowler’s Javascript Refac...
Side by Side - Scala and Java Adaptations of Martin Fowler’s Javascript Refac...
 
Ramda lets write declarative js
Ramda   lets write declarative jsRamda   lets write declarative js
Ramda lets write declarative js
 

Viewers also liked

Scala meetup - Intro to spark
Scala meetup - Intro to sparkScala meetup - Intro to spark
Scala meetup - Intro to sparkJavier Arrieta
 
CabMe|intercity travels
CabMe|intercity travelsCabMe|intercity travels
CabMe|intercity travelsSHUBHAM GUPTA
 
CabMe(intercity travels)
CabMe(intercity travels)CabMe(intercity travels)
CabMe(intercity travels)SHUBHAM GUPTA
 
Towards Aggregate Programming in Scala
Towards Aggregate Programming in ScalaTowards Aggregate Programming in Scala
Towards Aggregate Programming in ScalaRoberto Casadei
 
How To Use Higher Order Functions in Scala
How To Use Higher Order Functions in ScalaHow To Use Higher Order Functions in Scala
How To Use Higher Order Functions in ScalaBoldRadius Solutions
 
HDFS & MapReduce
HDFS & MapReduceHDFS & MapReduce
HDFS & MapReduceSkillspeed
 
Spark手把手:[e2-spk-s03]
Spark手把手:[e2-spk-s03]Spark手把手:[e2-spk-s03]
Spark手把手:[e2-spk-s03]Erhwen Kuo
 
Spark手把手:[e2-spk-s02]
Spark手把手:[e2-spk-s02]Spark手把手:[e2-spk-s02]
Spark手把手:[e2-spk-s02]Erhwen Kuo
 
Spark手把手:[e2-spk-s01]
Spark手把手:[e2-spk-s01]Spark手把手:[e2-spk-s01]
Spark手把手:[e2-spk-s01]Erhwen Kuo
 
Spark手把手:[e2-spk-s04]
Spark手把手:[e2-spk-s04]Spark手把手:[e2-spk-s04]
Spark手把手:[e2-spk-s04]二文 郭
 
Introduction to parallel and distributed computation with spark
Introduction to parallel and distributed computation with sparkIntroduction to parallel and distributed computation with spark
Introduction to parallel and distributed computation with sparkAngelo Leto
 
Run Your First Hadoop 2.x Program
Run Your First Hadoop 2.x ProgramRun Your First Hadoop 2.x Program
Run Your First Hadoop 2.x ProgramSkillspeed
 
Getting started with Apache Spark
Getting started with Apache SparkGetting started with Apache Spark
Getting started with Apache SparkHabib Ahmed Bhutto
 
Functional Programming for OO Programmers (part 1)
Functional Programming for OO Programmers (part 1)Functional Programming for OO Programmers (part 1)
Functional Programming for OO Programmers (part 1)Calvin Cheng
 
Spark徹底入門 #cwt2015
Spark徹底入門 #cwt2015Spark徹底入門 #cwt2015
Spark徹底入門 #cwt2015Cloudera Japan
 

Viewers also liked (20)

ScalaTrainings
ScalaTrainingsScalaTrainings
ScalaTrainings
 
Scala meetup - Intro to spark
Scala meetup - Intro to sparkScala meetup - Intro to spark
Scala meetup - Intro to spark
 
CabMe|intercity travels
CabMe|intercity travelsCabMe|intercity travels
CabMe|intercity travels
 
CabMe(intercity travels)
CabMe(intercity travels)CabMe(intercity travels)
CabMe(intercity travels)
 
[Start] Scala
[Start] Scala[Start] Scala
[Start] Scala
 
Towards Aggregate Programming in Scala
Towards Aggregate Programming in ScalaTowards Aggregate Programming in Scala
Towards Aggregate Programming in Scala
 
Spark Jobserver
Spark JobserverSpark Jobserver
Spark Jobserver
 
How To Use Higher Order Functions in Scala
How To Use Higher Order Functions in ScalaHow To Use Higher Order Functions in Scala
How To Use Higher Order Functions in Scala
 
HDFS & MapReduce
HDFS & MapReduceHDFS & MapReduce
HDFS & MapReduce
 
Spark手把手:[e2-spk-s03]
Spark手把手:[e2-spk-s03]Spark手把手:[e2-spk-s03]
Spark手把手:[e2-spk-s03]
 
Spark手把手:[e2-spk-s02]
Spark手把手:[e2-spk-s02]Spark手把手:[e2-spk-s02]
Spark手把手:[e2-spk-s02]
 
Spark手把手:[e2-spk-s01]
Spark手把手:[e2-spk-s01]Spark手把手:[e2-spk-s01]
Spark手把手:[e2-spk-s01]
 
Spark手把手:[e2-spk-s04]
Spark手把手:[e2-spk-s04]Spark手把手:[e2-spk-s04]
Spark手把手:[e2-spk-s04]
 
Introduction to parallel and distributed computation with spark
Introduction to parallel and distributed computation with sparkIntroduction to parallel and distributed computation with spark
Introduction to parallel and distributed computation with spark
 
Scala+RDD
Scala+RDDScala+RDD
Scala+RDD
 
Run Your First Hadoop 2.x Program
Run Your First Hadoop 2.x ProgramRun Your First Hadoop 2.x Program
Run Your First Hadoop 2.x Program
 
Getting started with Apache Spark
Getting started with Apache SparkGetting started with Apache Spark
Getting started with Apache Spark
 
Scala+spark 2nd
Scala+spark 2ndScala+spark 2nd
Scala+spark 2nd
 
Functional Programming for OO Programmers (part 1)
Functional Programming for OO Programmers (part 1)Functional Programming for OO Programmers (part 1)
Functional Programming for OO Programmers (part 1)
 
Spark徹底入門 #cwt2015
Spark徹底入門 #cwt2015Spark徹底入門 #cwt2015
Spark徹底入門 #cwt2015
 

Similar to Functional Programming for OO Programmers (part 2)

Thinking Functionally with JavaScript
Thinking Functionally with JavaScriptThinking Functionally with JavaScript
Thinking Functionally with JavaScriptLuis Atencio
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsEelco Visser
 
Composition birds-and-recursion
Composition birds-and-recursionComposition birds-and-recursion
Composition birds-and-recursionDavid Atchley
 
From Javascript To Haskell
From Javascript To HaskellFrom Javascript To Haskell
From Javascript To Haskellujihisa
 
Functional Programming In Java
Functional Programming In JavaFunctional Programming In Java
Functional Programming In JavaAndrei Solntsev
 
FunctionalJS - George Shevtsov
FunctionalJS - George ShevtsovFunctionalJS - George Shevtsov
FunctionalJS - George ShevtsovGeorgiy Shevtsov
 
1. George Shevtsov - Functional JavaScript
1. George Shevtsov - Functional JavaScript1. George Shevtsov - Functional JavaScript
1. George Shevtsov - Functional JavaScriptInnovecs
 
Functions in advanced programming
Functions in advanced programmingFunctions in advanced programming
Functions in advanced programmingVisnuDharsini
 
TDC2016SP - Trilha Programação Funcional
TDC2016SP - Trilha Programação FuncionalTDC2016SP - Trilha Programação Funcional
TDC2016SP - Trilha Programação Funcionaltdc-globalcode
 
Composition in JavaScript
Composition in JavaScriptComposition in JavaScript
Composition in JavaScriptJosh Mock
 
Functional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis AtencioFunctional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis AtencioLuis Atencio
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with GroovyArturo Herrero
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 
Functional aspects of java 8
Functional aspects of java 8Functional aspects of java 8
Functional aspects of java 8Jobaer Chowdhury
 
Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8RichardWarburton
 
Functional programming basics
Functional programming basicsFunctional programming basics
Functional programming basicsopenbala
 
Swift the implicit parts
Swift the implicit partsSwift the implicit parts
Swift the implicit partsMaxim Zaks
 

Similar to Functional Programming for OO Programmers (part 2) (20)

Thinking Functionally with JavaScript
Thinking Functionally with JavaScriptThinking Functionally with JavaScript
Thinking Functionally with JavaScript
 
Javascript
JavascriptJavascript
Javascript
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
 
Composition birds-and-recursion
Composition birds-and-recursionComposition birds-and-recursion
Composition birds-and-recursion
 
From Javascript To Haskell
From Javascript To HaskellFrom Javascript To Haskell
From Javascript To Haskell
 
Functional Programming In Java
Functional Programming In JavaFunctional Programming In Java
Functional Programming In Java
 
FunctionalJS - George Shevtsov
FunctionalJS - George ShevtsovFunctionalJS - George Shevtsov
FunctionalJS - George Shevtsov
 
1. George Shevtsov - Functional JavaScript
1. George Shevtsov - Functional JavaScript1. George Shevtsov - Functional JavaScript
1. George Shevtsov - Functional JavaScript
 
Functions in advanced programming
Functions in advanced programmingFunctions in advanced programming
Functions in advanced programming
 
25-functions.ppt
25-functions.ppt25-functions.ppt
25-functions.ppt
 
TDC2016SP - Trilha Programação Funcional
TDC2016SP - Trilha Programação FuncionalTDC2016SP - Trilha Programação Funcional
TDC2016SP - Trilha Programação Funcional
 
Haskell 101
Haskell 101Haskell 101
Haskell 101
 
Composition in JavaScript
Composition in JavaScriptComposition in JavaScript
Composition in JavaScript
 
Functional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis AtencioFunctional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis Atencio
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with Groovy
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
Functional aspects of java 8
Functional aspects of java 8Functional aspects of java 8
Functional aspects of java 8
 
Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8
 
Functional programming basics
Functional programming basicsFunctional programming basics
Functional programming basics
 
Swift the implicit parts
Swift the implicit partsSwift the implicit parts
Swift the implicit parts
 

More from Calvin Cheng

FOSSASIA 2018 Self-Sovereign Identity with Hyperledger Indy/Sovrin
FOSSASIA 2018 Self-Sovereign Identity with Hyperledger Indy/SovrinFOSSASIA 2018 Self-Sovereign Identity with Hyperledger Indy/Sovrin
FOSSASIA 2018 Self-Sovereign Identity with Hyperledger Indy/SovrinCalvin Cheng
 
iOS Beginners Lesson 4
iOS Beginners Lesson 4iOS Beginners Lesson 4
iOS Beginners Lesson 4Calvin Cheng
 
iOS Beginners Lesson 3
iOS Beginners Lesson 3iOS Beginners Lesson 3
iOS Beginners Lesson 3Calvin Cheng
 
iOS Beginners Lesson 2
iOS Beginners Lesson 2iOS Beginners Lesson 2
iOS Beginners Lesson 2Calvin Cheng
 
iOS Beginners Lesson 1
iOS Beginners Lesson 1iOS Beginners Lesson 1
iOS Beginners Lesson 1Calvin Cheng
 
So, you want to build a Bluetooth Low Energy device?
So, you want to build a Bluetooth Low Energy device?So, you want to build a Bluetooth Low Energy device?
So, you want to build a Bluetooth Low Energy device?Calvin Cheng
 
Learning iOS and hunting NSZombies in 3 weeks
Learning iOS and hunting NSZombies in 3 weeksLearning iOS and hunting NSZombies in 3 weeks
Learning iOS and hunting NSZombies in 3 weeksCalvin Cheng
 
Django101 geodjango
Django101 geodjangoDjango101 geodjango
Django101 geodjangoCalvin Cheng
 
Saving Gaia with GeoDjango
Saving Gaia with GeoDjangoSaving Gaia with GeoDjango
Saving Gaia with GeoDjangoCalvin Cheng
 
Agile Apps with App Engine
Agile Apps with App EngineAgile Apps with App Engine
Agile Apps with App EngineCalvin Cheng
 

More from Calvin Cheng (14)

FOSSASIA 2018 Self-Sovereign Identity with Hyperledger Indy/Sovrin
FOSSASIA 2018 Self-Sovereign Identity with Hyperledger Indy/SovrinFOSSASIA 2018 Self-Sovereign Identity with Hyperledger Indy/Sovrin
FOSSASIA 2018 Self-Sovereign Identity with Hyperledger Indy/Sovrin
 
Hashgraph as Code
Hashgraph as CodeHashgraph as Code
Hashgraph as Code
 
iOS Beginners Lesson 4
iOS Beginners Lesson 4iOS Beginners Lesson 4
iOS Beginners Lesson 4
 
iOS Beginners Lesson 3
iOS Beginners Lesson 3iOS Beginners Lesson 3
iOS Beginners Lesson 3
 
iOS Beginners Lesson 2
iOS Beginners Lesson 2iOS Beginners Lesson 2
iOS Beginners Lesson 2
 
iOS Beginners Lesson 1
iOS Beginners Lesson 1iOS Beginners Lesson 1
iOS Beginners Lesson 1
 
So, you want to build a Bluetooth Low Energy device?
So, you want to build a Bluetooth Low Energy device?So, you want to build a Bluetooth Low Energy device?
So, you want to build a Bluetooth Low Energy device?
 
Fabric
FabricFabric
Fabric
 
Learning iOS and hunting NSZombies in 3 weeks
Learning iOS and hunting NSZombies in 3 weeksLearning iOS and hunting NSZombies in 3 weeks
Learning iOS and hunting NSZombies in 3 weeks
 
Ladypy 01
Ladypy 01Ladypy 01
Ladypy 01
 
zhng your vim
zhng your vimzhng your vim
zhng your vim
 
Django101 geodjango
Django101 geodjangoDjango101 geodjango
Django101 geodjango
 
Saving Gaia with GeoDjango
Saving Gaia with GeoDjangoSaving Gaia with GeoDjango
Saving Gaia with GeoDjango
 
Agile Apps with App Engine
Agile Apps with App EngineAgile Apps with App Engine
Agile Apps with App Engine
 

Recently uploaded

Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfCionsystems
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 

Recently uploaded (20)

Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdf
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 

Functional Programming for OO Programmers (part 2)

  • 1. FUNCTIONAL PROGRAMMING for OO programmers (Part 2)
  • 2. WHAT • Pure versus Impure (exercise) • Currying (exercise) • Map, Filter, Reduce (exercise) • Functors,Applicative Functors, Monads (exercise) are we diving into?
  • 3. PURE OR IMPURE recognize pure functions
  • 4. RECOGNIZE • Functions that don’t change anything out-of-scope and don’t depend on anything out-of-scope are called “pure” • A pure function always gives the same result given the same parameters; independent of program/ system state pure functions
  • 5. RECOGNIZE pure function var  values  =  {  a:  1  };   function  pureFunction  (a)  {      var  b  =  1;      a  =  a  *  b  +  2;      return  a;   }  
  • 6. RECOGNIZE impure function var  values  =  {  a:  1  };   function  impureFunction  (items)  {      var  b  =  1;      items.a  =  items.a  *  b  +  2;      return  items;   }  
  • 8. PURE OR IMPURE? function  getQueryVariable(variable)  {      var  query  =  window.location.search.substring(1);      var  vars  =  query.split('&');      for  (var  i  =  0;  i  <  vars.length;  i++)  {              var  pair  =  vars[i].split('=');              if  (decodeURIComponent(pair[0])  ===  variable)  {                          return  decodeURIComponent(pair[1]);                      }          }   }
  • 9. PURE OR IMPURE? function  random(mZ,  mW)  {      mZ  =  36969  *  (mZ  &  65535)  +  (mZ  >>  16);      mW  =  18000  *  (mW  &  65535)  +  (mW  >>  16);      return  (mZ  >>  16)  +  mW;   }  
  • 10. PURE OR IMPURE? function  addAndShow(a,  b,  console)  {      var  c  =  a  +  b;      console.log(a,  '  +  ',  b,  '  =  ',  c);      return  c;   };  
  • 11. PURE OR IMPURE? var  number  =  1;   var  increment  =  function()  {      return  number  +=  1;   };   increment();  
  • 12. PURE OR IMPURE? var  number  =  1;   var  incrementAlt  =  function(n)  {          return  n  +  1;   };   incrementAlt(number);
  • 13. CURRYING first-order function and higher-order function capabilities
  • 14. CURRYING var  people  =  [      {  name:  'Calvin'  },      {  name:  'John'  },      {  name:  'Thomas'  }   ];   //  function  with  hardcoded  key  'name'  to  retrieve  list  of  names   function  getPersonName(obj)  {      return  obj['name'];   }   //  mapping  to  the  hardcoded  function   var  names  =  people.map(getPersonName);   console.log(names); JavaScript
  • 15. CURRYING //  Specify  the  key  on-­‐the-­‐fly  by  using  a  generic  function.   function  getByKey(key,  obj)  {      return  function(obj)  {          return  obj[key];      };   }   JavaScript
  • 16. CURRYING function  getByKey(key,  obj)  {      return  function(obj)  {          return  obj[key];      };   }   var  getByKeyPartial  =  getByKey('name');   console.log(getByKeyPartial);   var  names2  =  people.map(getByKeyPartial);   console.log(names2);   [Function] curried function or partial function JavaScript
  • 17. CURRYING function  getByKey(key,  obj)  {      return  function(obj)  {          return  obj[key];      };   }   var  names3  =  people.map(getByKey('name'));   console.log(names3); [Function] curried function or partial function equivalent to: getByKey(‘name’)(obj) in this context JavaScript
  • 18. CURRYING module  Main  where   f  ::  Integer   f  =  max  4  5   fPartial  ::  (Ord  a,  Num  a)  =>  a  -­‐>  a     fPartial  =  max  4   main  ::    IO  ()   main  =  do      print  f        let  g  =  fPartial  10      print  g Haskell
  • 19. CURRYING people  ::    [(String,  String)]   people  =  [("name",  "Calvin")          ,("wat",  "John")          ,("name",  "Thomas")          ]   Haskell
  • 20. CURRYING {-­‐  generic  filterByKey  function  that  accepts  a  string  as   keyname  and  the  data  structure  shown  previously  -­‐}   filterByKey  ::  Eq  a  =>  a  -­‐>  [(a,  t)]  -­‐>  [t]   filterByKey  _  []  =  []   filterByKey  p  ((k,  v):xs)          |  p  ==  k        =  v  :  filterByKey  p  xs          |  otherwise  =  filterByKey  p  xs   filterByName  ::  [(String,  t)]  -­‐>  [t]   filterByName  =  filterByKey  "name" Haskell [Function] curried function or partial function
  • 21. CURRYING main  ::    IO  ()   main  =  do          let  names2  =  filterByKey  "name"  people          print  names2          let  names3  =  filterByName  people          print  names3   Haskell [Function] curried function or partial function
  • 22. MAP, FILTER, REDUCE Look ma, no loops
  • 23. MAP, FILTER, REDUCE //  map,  reduce  and  filter  are  built-­‐in  as  methods  of  the     //  Array  class  in  JS   var  aList  =  [0,  1,  2];   var  newList  =  aList.map(function  (i)  {      return  i  +  1;   });   console.log(newList);   console.log(aList); JavaScript map
  • 24. MAP, FILTER, REDUCE aList  ::    [Integer]   aList  =  [0,  1,  2]   addOne  ::  [Integer]   addOne  =  map  (+1)  aList   Haskell map
  • 25. MAP, FILTER, REDUCE //  map,  reduce  and  filter  are  built-­‐in  as  methods  of  the     //  Array  class  in  JS   var  aList  =  [0,  1,  2];   var  lessThanTwo  =  aList.filter(function  (i)  {      return  i  <  2;   });   console.log(lessThanTwo);   console.log(aList); JavaScript filter
  • 26. MAP, FILTER, REDUCE aList  ::    [Integer]   aList  =  [0,  1,  2]   lessThanTwo  ::  [Integer]   lessThanTwo  =  filter  (<2)  aList   Haskell filter
  • 27. MAP, FILTER, REDUCE //  map,  reduce  and  filter  are  built-­‐in  as  methods  of  the     //  Array  class  in  JS   var  aList  =  [0,  1,  2];   var  reduceToSum  =  aList.reduce(function  (a,  b)  {      return  a  +  b;   });   console.log(reduceToSum);   console.log(aList);   reduce
  • 28. MAP, FILTER, REDUCE aList  ::    [Integer]   aList  =  [0,  1,  2]   reduceToSum  ::  Integer   reduceToSum  =  foldl  (+)  0  aList   Haskell reduce (foldl and foldr)
  • 29. FUNCTORS a function that, given a value and a function, does the right thing
  • 30. FUNCTORS function  addOne(value)  {      return  value  +  1;   }   console.log(addOne(10));    //  11   function  addTwo(value)  {      return  value  +  2;   }   console.log(addTwo(10));    //  12   JavaScript
  • 31. FUNCTORS //  A  not-­‐quite-­‐there  Functor   function  aFunctor(value,  fn)  {      return  fn(value);   }   console.log(aFunctor(10,  addOne));  //  11,  works  as  expected   console.log(aFunctor([1,  2,  3],  addOne));    //  '1,2,31'  is   returned,  which  is  not  what  we  want   JavaScript
  • 32. FUNCTORS function  betterFunctor(value,  fn)  {      if  (typeof  value  ===  'number')  {          return  fn(value);        }  else  {          var  map  =  Array.prototype.map;          return  map.call(value,  fn);      }   }   JavaScript
  • 33. FUNCTORS console.log(betterFunctor([1,  2,  3],  addOne));    //  [2,  3,   4]  is  what  we  expected   console.log(betterFunctor(10,  addOne));                  //  11  is   what  we  expected   JavaScript
  • 34. FUNCTORS //  JavaScript's  Array's  map  method  is  a  functor!  :-­‐)   var  map  =  Array.prototype.map;   console.log(map.call([1,  2,  3],  addOne));              //  [2,  3,   4]  is  what  we  expected.     console.log([].map.call([1,  2,  3],  addOne));        //  This   works  too   JavaScript
  • 35. FUNCTORS addOne  ::    Num  a  =>  a  -­‐>  a   addOne  a  =  a  +  1   addTwo  ::    Num  a  =>  a  -­‐>  a   addTwo  a  =  a  +  2   result  ::    Num  b  =>  [b]  -­‐>  [b]   result  xs  =    map  addOne  xs   Haskell
  • 36. COMPARISON Functors vs Applicative Functors vs Monads Functors Applicatives Monads example (+3) [2] == [5] Just(+3) <*> Just 2 == Just 5 Just 4 >>= makeHalf == Just 2 examples functions map, fmap, <*> <*>, <$>, liftA2 >>=, liftM brings function operator in execute operationgeneralized map does both <*> & <$> apply fn to wrapped value apply wrapped fn to wrapped value apply fn that returns a wrapped value to a wrapped value
  • 37. MAYBE FUNCTORS an often-used functor; and more about functors
  • 38. MAYBE FUNCTORS • Captures null check • Value inside may or may not be there • Maybe has two subclasses - ‘Just’ or ‘Nothing’ (Haskell) • Also referred to as Option with subclasses ‘Some’ or ‘None’ (Scala) • Also available in Swift, e.g. Optional, enum Either<NSError, User>
  • 39. MAYBE FUNCTORS var  aList  =  [1,  2,  3];   function  compose(f,  g)  {      return  function  (x)  {          return  f(g(x));      };   }   function  addOne(value)  {      return  value  +  1;   }   function  addTwo(value)  {      return  value  +  2;   } JavaScript
  • 40. MAYBE FUNCTORS console.log(aList.map(compose(addOne,  addTwo)));   console.log(aList.map(addTwo).map(addOne));   function  mayBe(value,  fn)  {      return  value  ===  null  ||  value  ===  undefined  ?  value  :   fn(value);   }   JavaScript
  • 41. MAYBE FUNCTORS console.log(mayBe(undefined,  compose(addOne,  addTwo)));           //  returns  expected  result  undefined   console.log(mayBe(mayBe(undefined,  addTwo),  addOne));               //  returns  expected  result  undefined   console.log(mayBe(1,  compose(addOne,  addTwo)));                           //  returns  expected  result  4     console.log(mayBe(mayBe(1,  addTwo),  addOne));                               //  returns  expected  result  4   JavaScript
  • 42. MAYBE FUNCTORS addOne  ::    Num  a  =>  a  -­‐>  a   addOne  a  =  a  +  1   addTwo  ::    Num  a  =>  a  -­‐>  a   addTwo  a  =  a  +  2   composedFn  ::    Integer  -­‐>  Integer   composedFn  =  addOne  .  addTwo   res  ::    [Integer]   res  =  map  composedFn  aList Haskell
  • 43. MAYBE FUNCTORS main  ::    IO  ()   main  =  do          print  res          let  res2  =  fmap  composedFn  Nothing          print  res2          let  res3  =  fmap  composedFn  (Just  1)          print  res3 Haskell
  • 45. APPLICATIVES var  none  =  {          map:  function()  {                  return  none;          },          bind:  function()  {                  return  none;          },                    toString:  function()  {                  return  'none';          }   }; JavaScript
  • 46. APPLICATIVES function  some(value)  {          return  {                  map:  function(func)  {                          return  some(func(value));                  },                                    bind:  function(func)  {                          return  func(value);                  },                                    toString:  function()  {                          return  "some("  +  value  +  ")";                  }          };   }   JavaScript
  • 47. APPLICATIVES var  functor  =  {          map:  function(func,  option)  {                  return  option.map(func);          },          unit:  some,          applyFunctor:  function(funcOption,  argOption)  {                  return  funcOption.bind(function(func)  {                          return  argOption.map(func);                  });          }   }; JavaScript
  • 48. APPLICATIVES function  curry(func,  numberOfArguments)  {      return  function(value)  {          if  (numberOfArguments  ===  1)  {              return  func(value);          }  else  {              return  curry(func.bind(null,  value),  numberOfArguments  -­‐  1);          }      };   } JavaScript
  • 49. APPLICATIVES //  Usage   var  four  =  some(4);   var  six  =  some(6);   console.log(four.toString());   console.log(six.toString());   function  add(a,  b)  {      return  a  +  b;   }   var  result  =  functor.applyFunctor(functor.map(curry(add,  2),  four),  six);   console.log(result.toString());  //  some(10) JavaScript
  • 50. APPLICATIVES result  =  functor.applyFunctor(functor.map(curry(add,  2),   none),  six);   console.log(result.toString());   result  =  functor.applyFunctor(functor.map(curry(add,  2),   four),  none);   console.log(result.toString()); JavaScript
  • 51. APPLICATIVES //  A  cleaner  API  for  our  applicative  functor  operations   functor.applyFunctorUncurried  =  function(func)  {      var  args  =  Array.prototype.slice.call(arguments,  1);      return  args.reduce(          functor.applyFunctor,          functor.unit(curry(func,  args.length))      );   };   JavaScript
  • 52. APPLICATIVES var  result2  =  functor.applyFunctorUncurried(add,  four,  six);   console.log(result2.toString());   result2  =  functor.applyFunctorUncurried(add,  none,  six);   console.log(result2.toString());   result2  =  functor.applyFunctorUncurried(add,  four,  none);   console.log(result2.toString());   JavaScript
  • 53. APPLICATIVES import  Control.Applicative   ans  ::    Maybe  Integer   ans  =  (+)  <$>  Just  4  <*>  Just  6   main  ::    IO  ()   main  =  print  ans   Haskell
  • 54. MONADS apply function that returns wrapped value to a wrapped value
  • 55. MONAD “A monad is just a monoid in the category of endofunctors, what's the problem?” - James Iry (Brief, Incomplete and Mostly Wrong History of Programming Languages)
  • 56. MONAD Let’s • understand the why, • then, illustrate the how • and, we will know what a monad is.
  • 57. MONAD Why? avoid mutable state while chaining a group of functions together (or executing a sequence of logic)
  • 58. MONAD mutation: functions in imperative languages change the state of values as logic is executed
  • 59. MONAD So what’s the big deal? When data is mutable, parallel thread execution of your code on multiple CPUs leads to race conditions Can’t do parallel thread execution on your multi-core machine idle resource If we insist on parallel thread execution without locks unpredictable results, i.e. errors
  • 60. MONAD
  • 61. MONAD f (x) x = g(x) x = h(x) x = i(x) return x
  • 62. MONAD f (x) x = g(x) x = h(x) x = i(x) return x x = 3 x = 5 x = 10 x = -3 x = -3
  • 63. f (x) x = g(x) x = h(x) x = i(x) return x f (x) x = g(x) x = h(x) x = i(x) return x MONAD x = 3 x = 5 x = 17 x = 4 x = -9 x = 7 x = 12 CPU #1 CPU #2 x = 4 x = -9 Shared Memory, x
  • 64. MONAD As you can see, the same function results in indeterminate results depending on the whims of the parallel OS- controlled POSIX threads (“pthreads”) We expect that when we write the code (“computation logic”) for f(x), when given x = 3, f(x) will always result in -3 but because x is mutable in traditional languages, this is not the case if we try to make our program run on multiple CPUs.
  • 65. MONAD Imperative languages that we are familiar with solve this problem with • locks (semaphores) on POSIX threads; or • green threads (concurrent threads) and asynchronous I/O
  • 66. MONAD Haskell has everything + more performant approaches: • sparks (super-duper lightweight green threads) • green threads • semaphores • immutable variables by default,“side effects” (mutability) achieved via monads
  • 67. f (x) x1 = g(x) x2 = h(x1) x3 = i(x2) return x3 f (x) x1 = g(x) x2 = h(x1) x3 = i(x2) return x3 MONAD x = 3 x1 = 5 x2 = 10 x3 = -3 x3 = -3 x1 = 5 x2 = 10 CPU #1 CPU #2 x3 = -3 x3 = -3
  • 68. MONAD Haskell f :: Num a => a -> a f x = let x1 = x + 2 x2 = x1 + 5 x3 = x2 - 13 in x3 f :: Num a => a -> a f x = let x = x + 2 x = x + 5 x = x - 13 in x error: variables in haskell are immutable values! no side effects!
  • 69. MONAD So, now, we know the Why? avoid mutable state while chaining a group of functions together (or executing a sequence of logic) So, how can a monad achieve the magic illustrated in the previous 2 slides?
  • 71. MONAD var  Maybe  =  function(value)  {  //  container      this.value  =  value;   };   Maybe.prototype.ret  =  function()  {    //  return      return  this.value;   };   Maybe.prototype.bind  =  function(func)  {    //  bind      if  (this.value  !==  null)  {          return  func(this.value);      }      return  this.value;   }; JavaScript
  • 72. MONAD //  lift:  takes  in  a  function  that  returns  a  normal  value  and  changes  it  in  a  monad   Maybe.lift  =  function(func)  {      return  function(value)  {          return  new  Maybe(func(value));      };   };   //  Usage   var  addOne  =  function(value)  {      return  value  +  1;   };   //  we  can  use  this  with  bind   var  maybeAddOne  =  Maybe.lift(addOne); JavaScript
  • 73. MONAD //  lift2  use  closures  to  get  values  from  the  two  monads     //  before  running  it  through  function,  handling  the  undefined  cases   Maybe.lift2  =  function(func)  {      return  function(M1,  M2)  {          return  new  Maybe(M1.bind(function(value1){              return  M2.bind(function(value2)  {                  return  func(value1,  value2);              });          }));      };   }; JavaScript
  • 74. MONAD var  add  =  function(a,  b)  {return  a  +  b;};   var  m1  =  new  Maybe(1);   var  m2  =  new  Maybe(2);   var  m3  =  new  Maybe(undefined);   var  liftM2Add  =  Maybe.lift2(add);   liftM2Add(m1,  m2).ret();  //3   liftM2Add(m3,  m2).ret();  //undefined   liftM2Add(m1,  m3).ret();  //undefined   JavaScript
  • 75. MONAD a  ::    Maybe  Integer   a  =  Just  1   f  ::    Integer  -­‐>  Maybe  Integer   f  =  x  -­‐>  Just  (x  +  1)   main  ::    IO  ()   main  =  do      let  ans  =  a  >>=  f      print  ans    {-­‐  we  expect  to  get  Just  2  -­‐} Haskell
  • 76. MONAD • type container • return • bind • We pass in function(s) to operate values inside it • and get a returned value
  • 79. CRAFTSMANSHIP Master your craft - Procedural, OO, Functional