dimitris papadimitriou
dimitris papadimitriou More than 12 years’ experience as full stack developer and Software Architect . Functional javascript with categories.

IO functor

IO functor

…continuing from Lazy Functor

Functional programming in the same lines provides the IO functor

1
2
3
4
 var IO = fn => ({
  map: f => IO(() => f(fn())), 
  run: () => fn(), 
 })

Ithe map implementation should remind you slightly of the promise map line of reasoning while implementing it.

  1. We first have to “run” the previous computation fn()
  2. then use the function f to get the lifted value f(fn())
  3. and then finally rewrap this new value in a
1
new IO(() => f(fn()))

An example application coming from the frontend web design universe uses IO, to isolate the effects of accessing the DOM elements with jQuery

1
2
3
4
5
6
var getJqueryElementIO = IO(() => $("#container"));

var title = getHtmlElementIO
.map(x=>x.text())
.map(x.toUpperCase())
.run()

Run This: Js Fiddle

It’s the same as the Id functor but encloses the value that we provide in a thunk () => { } just to make it lazy. We would have to collapse the function fn() in order to get back the value, most IO implementations around usually provide a run () function that does just that. You can take a look at monet.js library implementation of IO. Also, with a prototype extension on the Object, we can create IOs out of everything on the fly

1
Object.prototype.toIO = function () { return IO(() => this); }

And use it like this:

1
var getJqueryElementIO = $("#container").toIO ();

Run This: Js Fiddle

The Lazy loading design pattern (with the map method) is Isomorphic to the IO Functor


Excerpt from the Book Functional Programming in Javascript in LeanPub https://leanpub.com/functional-programming-in-js-with-categories

comments powered by Disqus