Functor, Pointed Functor, Monad and Applicative Functor in JS

function-machine

// This post will briefly explain (omiting, skipping some parts) in code what is
// Functor, Pointed Functor, Monad and Applicative Functor. Maybe by reading the
// code you will easily grasp these functional concepts.
// if you only want to run this code go to:
// https://jsfiddle.net/leandromoreira/buq5mnyk/
// or https://gist.github.com/leandromoreira/9504733c7f8c6361c46270ea953d8409
// This code requires you to have require.js loaded (or you can load ramda instead :P)
requirejs.config({
paths: {
ramda: 'https://cdnjs.cloudflare.com/ajax/libs/ramda/0.13.0/ramda.min'
},
});
require(['ramda'], function(_) {
// First let's create a Container that is a type that holds (wraps) a value, a useful abstraction to handle state.
var Container = function(x) {
this.__value = x;
}
// of is a method to create Container of x type
Container.of = function(x) {
return new Container(x);
};
console.log("should be 3", Container.of(3))
// We can improve this building block (Container) by providing a way to handle the wrapped value,
// this is basically a Functor, which is a type that implements map (it is mappable) and obeys some laws.
// By the way a Pointed Functor is a functor with an of method.
Container.prototype.map = function(f) {
return Container.of(f(this.__value));
}
var c4 = Container.of(4)
var inc = function(x) {
return x + 1
}
var c5 = c4.map(inc)
// We first created a container of 4 then we map a increase over it resulting in a container of 5
console.log("should be 5", c5)
// Maybe is a functor that checks if the value is null/undefined
// it is useful to avoid erros like "Cannot read property x of null"
Container.prototype.isNothing = function() {
return (this.__value === null || this.__value === undefined);
};
// Now our map will also check weather it's valid or not.
Container.prototype.map = function(f) {
return this.isNothing() ? Container.of(null) : Container.of(f(this.__value));
};
var address = function(person) {
return person.address;
};
var upperCase = function(t) {
return t.toUpperCase()
}
// Although we're passing an invalid value to the container it won't broke
console.log("should be null without errors", Container.of(null).map(address).map(upperCase))
// but when we do pass the right parameter it produces the expected output
console.log("should be HERE", Container.of({
name: "Diddy",
address: "here"
}).map(address).map(upperCase))
// this is good but a failing error with no message can make things worst ūüė¶
// This functions maps any function a functor
var map = _.curry(function(ordinaryFn, functor) {
return functor.map(ordinaryFn);
});
var aFunctor = Container.of(2)
var sum6 = function(x) {
return x + 6
}
// given an ordinary function and an functor it produces another functor
var plus6 = map(sum6)
var y = plus6(aFunctor)
console.log("should be a Functor of 8", y)
// Either is a functor that can return two types either Right (normal flow) or Left (some error occorred).
// Now here what is great is that we can say what was the error.
var Left = function(x) {
this.__value = x;
};
Left.of = function(x) {
return new Left(x);
};
Left.prototype.map = function(f) {
return this;
};
var Right = function(x) {
this.__value = x;
};
Right.of = function(x) {
return new Right(x);
};
Right.prototype.map = function(f) {
return Right.of(f(this.__value));
}
console.log("should be 10", Right.of(8).map(inc).map(inc))
console.log("should be unchaged 8", Left.of(8).map(inc).map(inc))
var nonNegative = function(x) {
if (x < 0) {
return Left.of("you must pass a positive number")
} else {
return Right.of(x)
}
}
console.log("should be 10", nonNegative(9).map(inc))
console.log("should be an error message", nonNegative(4).map(inc))
// IO is a functor that holds functions as values, and instead of mapping the value
// it'll map functions and compose them like a array of functions.
var IO = function(f) {
this.__value = f;
};
IO.of = function(x) {
return new IO(function() {
return x;
});
};
IO.prototype.map = function(f) {
return new IO(_.compose(f, this.__value));
};
var composedLazyFunctions = IO.of(3).map(inc).map(inc).map(inc)
console.log("this is a lazy composed function", composedLazyFunctions)
console.log("this is the execution of that composed function", composedLazyFunctions.__value())
var readFile = function(filename) {
return new IO(function() {
return "read file from " + filename
});
};
var print = function(x) {
return new IO(function() {
return x
});
};
// Cat will be a composed function that produces and IO of an IO :X
var cat = _.compose(map(print), readFile)
var catGit = cat('.git/config')
console.log("it should be an IO of IO IO(IO())", catGit)
// This creates an awkward situation where if we want the real value we need to
// catGit.__value().__value() how about create a join that unwraps the value.
IO.prototype.join = function() {
return this.__value()
};
console.log("should be 'read file from .git/config'", catGit.join().join())
// Notice that we still need to call join twice, and if we join every time we map?
// this is what we know was chain
var chain = _.curry(function(ordinaryFn, functor) {
return functor.map(ordinaryFn).join();
});
var complexSum = function(initialNumber) {
return new IO(function() {
var x = initialNumber * 4
var y = x * 4
return (y + 42) x * 4
});
};
var incIO = function(x) {
return new IO(function() {
return x + 1
});
};
var doubleIO = function(x) {
return new IO(function() {
return x * 2
});
};
var cleverMath = _.compose(
chain(doubleIO),
chain(incIO),
chain(incIO),
complexSum
);
var multiplier = Math.floor((Math.random() * 552) + 7)
var ordinaryValue = Math.floor((Math.random() * 98134123) 12)
var cleverMathResult = cleverMath(ordinaryValue * multiplier)
console.log("should be 88", cleverMathResult.join())
// Monads are pointed functors that can flatten ūüôā
// Now let's finish with an Applicative Functor which is a pointed functor with an ap(ply) method
Container.prototype.ap = function(other_container) {
return other_container.map(this.__value)
}
console.log("should be Container(4)", Container.of(inc).ap(Container.of(3)))
})
// Please consider to read these links bellow
// http://www.leonardoborges.com/writings/2012/11/30/monads-in-small-bites-part-i-functors/
// https://drboolean.gitbooks.io/mostly-adequate-guide/content/ch8.html

Functional Programing 101 :: WWH

function-machine

WWH: What? Why? How?

  1. What: a quick (hopefully, useful to real world) guide to functional programing using JavaScript strongly based on most adequate book.
  2. Why: it might empower you to write more robust programs: reusable, shorter, easier to reason about, less prone to error among others.
  3. How: by providing a quick textual introduction (WWH) followed by a simple code example and when possible a real code example.

Intro :: concepts

Functional Programing

What: a way to build code in which you use functions as the main design tool.

Why: might lead to code that’s easier to test, debug, parallelize, and understand.

How: thinking about what programs should do instead of how, using functions as the major unit to solve problems on computer.

First Class Functions

What: “functions are like any other data type and there is nothing particularly special about them – they may be stored in arrays, passed around, assigned to variables.”

Why: use functions to compose programs in a style that you can easily reason about, maintain, reuse and grow.

How: just create and use functions to solve problems.

// set to vars
var hi = function(name) {
return 'Hi ' + name
}
// rebound to other var
var greeting = hi
// an array of fns
var greetings = [hi, greeting]
// passed as arguments
var execIn1Second = function(fn) {
setTimeout(fn, 1000)
}

view raw
js.js
hosted with ❤ by GitHub

Pure Functions

What: “a function that, given the same input, will always return the same output and does not have any observable side effect.”

Why: with pure functions we can easily cache, debug, test and parallelize the processing of them. There is no state to understand / set up.

How: write functions that does not have side effect. Although we’ll eventually write programs that mutate values, we can certainly try to minimize it. (And when we do need to mutate values, we can use functions to help us)

// impure – because you can change promo value (side effect)
// and for the same input X it can produce a different output.
var promo = 40
var isPromo = function(price) {return price === promo}
// pure
var isPromo = function(price) {return price === 40}

view raw
pure.js
hosted with ❤ by GitHub

Basic toolbox :: currying

What: “You can call a function with fewer arguments than it expects. It returns a function that takes the remaining arguments.”

Why: you can promote the reusability to function level, you can use them to compose programs that expects another function

How: build a function with n parameters that returns n functions instead of the immediate result.

// an ordinary function
var sum = function(a, b){return a+b}
sum(1, 3) // 4
// a curried version of that sum
var curriedSum = function(a){
return function(b){return a+b}
}
var plusOne = curriedSum(1) // function(b) {return a+b}
plusOne(3) // 4
plusOne(1) // 2 -> plusOne is useful outside it's original scope
// a simple function to curry any other function
// we'll use this in future
// DO NOT USE THIS IN PRODUCTION
var curry = function(uncurriedFn){
var argumentsCall = []
return function curriedFn(){
var args = Array.prototype.slice.call(arguments)
if (args.length > 0) {
argumentsCall = argumentsCall.concat(args)
if (uncurriedFn.length == argumentsCall.length) {
return uncurriedFn.apply(this, argumentsCall)
}
}
return curriedFn
}
}
// an usage example of curry
var curriedAjax = curry(function(method, path){
return $.ajax(path, {method: method})
})
var ajaxGET = curriedAjax('GET')
var allUsers = ajaxGET('/users')
var allStars = ajaxGET('/stars')

view raw
curry.js
hosted with ❤ by GitHub

Medium toolbox :: composing

What: is the act of creating your programs using lots of functions.

Why: this promotes the reuse at a great level and forces you to think about what instead of how.

How: chain functions to produce a new callable function.

// a simple function to compose a function
// DO NOT USE THIS IN PRODUCTION
// you can skip the reading of this function if you want
var compose = function(){
var fns = Array.prototype.slice.call(arguments)
return function composed(){
var thisCall = this
var args = Array.prototype.slice.call(arguments)
fns.reverse().forEach(function(fn){
if (Object.prototype.toString.call(args) !== '[object Array]') args = [args]
args = fn.apply(thisCall, args)
})
return args
}
}
// take a list of Strings and return a list of up case strings
var toUpperCase = function(list) {
return list.map(function(x){return x.toUpperCase()})
}
// take a list of Strings and return a list of length
var length = function(list) {
return list.map(function(x){return x.length})
}
// take a list of Integer and return the sum
var sum = function(list) {
var sum = 0
list.forEach(function(x){sum += x})
return sum
}
// chain all these functions and produce a new
var sumCharsOnList = compose(sum, length, toUpperCase)
sumCharsOnList(["NX", "PS4", "XboxOne"])

view raw
composition.js
hosted with ❤ by GitHub

// brief explanation of what happens here
var sumCharsOnList = compose(sum, lenght, toUpperCase)
sumCharsOnList(["NX", "PS4", "XboxOne"])
// –> first the list ["NX", "PS4", "XboxOne"] is passed to the function toUpperCase
// –> toUpperCase returns another list and it's the input for the lenght function
// –> the lenght function return a list of integers which will become the input for sum function
// –> sum function will reduce the list summing all the integers and returning the sum

view raw
explanation.js
hosted with ❤ by GitHub

Example :: motivational

What: a better example to motivate you to go further with functional programing.

Why: most near real world examples are great to motivate you to learn something.

How: since you can see all the concepts together, I think you’ll notice the value.

You can see the example running at https://jsfiddle.net/swmrmgur/2/ and check the commented code down bellow.

Screen Shot 2016-04-27 at 2.17.19 PM

// _ is an instance of Ramda
// $ is an instance of jQuery
// This is an app extracted from the book
// mostly-adequate-guide/content/ch6.html
// it's query the flickr API's and mount
// a lots of images on the page
// IMPURE functions ahead
// takes a function (callback) and returns another
// function which takes an url
var getJSON = _.curry(function(callback, url) {
$.getJSON(url, callback);
})
// takes a selector and returns a functions
// which you can pass an html
var setHtml = _.curry(function(sel, html) {
$(sel).html(html);
})
// PURE, good and reliable functions ahead
// just create an image for a given url
var img = function(url) {
return $('<img />', {
src: url,
});
};
// just create an url for a given query
var url = function(t) {
return 'http://api.flickr.com/services/feeds/photos_public.gne?tags=&#39; +
t + '&format=json&jsoncallback=?';
};
// _.prop is a curried function which takes
// a property name and then an object
// ex: var getPrice = _.prop('price')
// getPrice({price: 3, x: "y"}) // returns 3
// takes an object extracts its media and
// then from the media it extracts the m property
var mediaUrl = _.compose(_.prop('m'), _.prop('media'));
// it takes a media url and create an image
var mediaToImg = _.compose(img, mediaUrl);
//it takes an object and extracts items from it
// map each one to an image
var images = _.compose(_.map(mediaToImg), _.prop('items'));
// it takes images and set
// them on the document.body
var renderImages = _.compose(setHtml('body'), images);
// given a string, it'll create an url and
// gets the json and render the images
var app = _.compose(getJSON(renderImages), url);
// given a query it'll create a page
app('cats');
// I strongly recommend you to read again from app to mediaUrl

view raw
flickr.js
hosted with ❤ by GitHub

Advanced toolbox & conclusion

I hope¬†you might see the benefits you can have from using one or other technique from functional programming but for sure there are other benefits not shown here, I strongly recommend you to read the INCREDIBLE free book (gitbook)¬†“Professor Frisby’s Mostly Adequate Guide to Functional Programming”, in fact, most of the ideas and examples here are from it.

There are advanced techniques to deal with data mutation with less pain, to handle errors and exceptions without try and catch and more abstractions that can help you and you can read them on the book.

And don’t use the handcrafted curry and compose built here (they’re far from production-ready), instead use a library like Ramda,¬†which provides many basic functions like: map, filter and other all of them already curried, or lodash-fp.

Yeah, there no monado here. A special thank to Daniel Martins and Juarez Bochi, they helped a lot.

cover

3 tips to make you a better developer

four20puzzle

introduction

I’m sorry for the clickbait headline, I didn’t have a better idea/name for it.

We (developers) occasionally¬†produce¬†lazy/messy code¬†and from time to time we need to remember¬†the most important rule:¬†“We do code to solve problems but also for human being¬†be able:¬†to use, to maintain and to evolute”.¬†

TLDR; (a unit can be a: function, var, method, class, parameter and etc)

  1. Naming your units with care and meaning;
  2. Try to see your code as a series of transformation;
  3. When possible make yours units generic.

Keep in mind that these tips are just my opinions and at the best they were based on:¬†excellent books (Refactoring, DDD, Clean Coder and etc¬†),¬†articles &¬†blog posts, ¬†excellent¬†people I’ve worked/paired with, ¬†presentations, ¬†tweets and¬†experiences.

naming is hard

Name your units with care and meaning. Your code should be easy to understand.

Although naming things is really hard, it is also¬†extremely important.¬†Let’s a see a snippet of code:

var topComments = (id) => {
var succCB = (d) => {
var a = d.data.comments
var top = []
a.sort((d1, d2) => {
return new Date(d1.date) new Date(d2.date)
})
a.forEach((c) => {
if (c.isTop()) {
top.push(c)
}
}
app.topComments = top.slice(0,10)
}
var errCB = (e) => {
this.sendError(e)
app.topComments = []
}
this.ajax(`/all/${id}/comments/`, succCB, errCB)
}

view raw
0-top-comments.js
hosted with ❤ by GitHub

Let’s discuss about this code above:

  • the¬†function topComments receives an id but is it the id from the comment, user, article? Let’s say it’s form the user, therefore¬†userId¬†should vanish this doubt.
  • the name of the function¬†is topComments but it looks like it’s getting the top 10 latest comments only¬†thus¬†we could call it top10LatestCommentsFrom.
  • the ajax function accept two callbacks one in case of success (succCB) and otherwise an error (errCB), I believe we can call them: onSuccess and onError for better understanding.
  • all the arguments are using short names and we can have¬†less confusing names just by using the entire name.
  • you got the ideia, naming things to let the code clear!
var top10LatestCommentsFrom = (userId) => {
var onSuccess = (rawData) => {
var topLatestComments = []
var allComments = rawData.data.comments
allComments = allComments.sort((date1, date2) => {
return new Date(date1.date) new Date(date1.date)
})
allComments.forEach((comment) => {
if (comment.isTop()) {
topLatestComments.push(comment)
}
}
app.topComments = topLatestComments.slice(0,10)
}
var onError = (error) => {
this.sendError(error)
app.topComments = []
}
this.ajax(`/all/${userId}/comments/`, onSuccess, onError)
}

view raw
1-top-comments.js
hosted with ❤ by GitHub

Although we still have so many problems in this code, now it’s easier to understand and¬†we only named things properly.

For sure there are some cases when short names are just okay, for example: when you’re¬†developing an emulator or virtual machine you often use short names like sp (stack pointer) and pc (program counter) or even doing a very generic unit.

class LR35902 {
init() {
this.pc = this.sp = 0x0000
this.a = this.b = this.c = this.d = this.e = this.f = this.f = this.h = this.l = 0x00
}
execute() {
var opCode = memory.read(this.pc)
this.perform(opCode)
this.pc += 2
}
}

view raw
cpu.js
hosted with ❤ by GitHub

filter -> union -> compact -> kick

Try to see and fit your code as transformations, one after another.

Some say that in computer science almost all the problems can be reduced to only two major problems: sort and count things (plus doing these in a distributed environment), anyway the point is: we usually are coding to make transformation over data.

For instance our function top10LatestCommentsFrom could be summarized in these steps:

  1. fetch comments (all)
  2. sort them (by date)
  3. filter them (only top)
  4. select the first 10

Which are just transformations over an initial list, we can make our function top10LatestCommentsFrom much better with that mindset.

var onError = (error) => this.sendError(error)
var byDate = (date1, date2) => new Date(date1.date) new Date(date1.date)
var onlyTops = (comment) => comment.isTop()
var top10LatestComments = (rawData) => {
app.topComments = rawData.data.comments
.sort(byDate)
.filter(onlyTops)
.slice(0, 10)
}
var userId = 68
ajax(`/${userId}`, top10LatestComments, onError)

view raw
2-top-comments.js
hosted with ❤ by GitHub

 

By the way this could lead you to easily understand the new kid on the block sometimes referred as Functional Reactive Programming.

<be generic>

Work to make your units generic.

Let’s imagine you are in an interview process and your first task is to code a function which prints the numbers 1, 2 and 3¬†concatenated with “Hello, “. It should print: “Hello, 1” and then “Hello, 2″…

var printNumbers = () => {
[1,2,3].forEach((number) => console.log(`Hello, ${number}`))
}
printNumbers()

view raw
interview1.js
hosted with ❤ by GitHub

Now they ask you to print also the letters: “D”, “K” and “C”.

var print = (list) => {
list.forEach((number) => console.log(`Hello, ${number}`))
}
print([1,2,3])
print(["D","K","C"])

view raw
print2.js
hosted with ❤ by GitHub

It was the first step toward the “generic”, now the interviewers¬†say you have also to print a list of person’s name but now it’ll be a list of objects [{name: “person”},…].

var print = (list) => {
list.forEach((item) => {
// naming become harder ūüė¶
var itemDescription
if (typeof item === "object") {
itemDescription = item.name
} else {
itemDescription = item
}
console.log(`Annyong, ${itemDescription}`)
})
}
print([1,2,3])
print(["d","k","c"])
print([{name: "Buster Lose Seal"}, {name: "Neo Cortex"}])

view raw
print-person.js
hosted with ❤ by GitHub

Things start to get¬†specific again and the interviewers want to test you. They ask you¬†to¬†print a list of car’s brand [{brand: “Ferrari”}, ..] plus a list of game consoles with their architecture [{name: “PS4”, arch: “x86-64”}, …]

var print = (list) => {
list.forEach((item) => {
var itemDescription
if (typeof item === "object") {
itemDescription = item.name || item.brand
if (item.arch) {
itemDescription = `${item.name}${item.arch}`
}
} else {
itemDescription = item
}
console.log(`Hello, ${itemDescription}`)
})
}
print([1,2,3])
print(["D","K","C"])
print([{name: "Buster Lose Seal"},{name: "Neo Cortex"}])
print([{brand: "Ferrari"}, {brand: "Mercedes"}])
print([{name: "N64", arch: "MIPS"}, {name: "3DS", arch: "ARM9"}])

view raw
print5.js
hosted with ❤ by GitHub

Yikes, I suppose you’re not proud of that code and probably your interviewers will be little concerned about your skills with development, let’s list some of the problems with this approach.

  • Naming (we’re calling a person of an item)
  • High coupling (the¬†function print knows too much about each printable)
  • Lots of (inner)¬†conditionals ūüė¶ it’s really hard to read/maintain/evolute this code

What we can do?! Well, it seems that all we need to do is to iterate through an array and prints an item but each item will require a different way of printing.

var defaultPrint = (item) => console.log(`Hello, ${item}`)
var myForEach = (list, printFunction = defaultPrint) => {
list.forEach((item) => printFunction(item))
}
myForEach([1,2,3])
myForEach(["D","K","C"])
myForEach([{name: "Tomba!"},{name: "Neo Cortex"}], (person) => defaultPrint(person.name))
myForEach([{brand: "Ferrari"}, {brand: "Mercedes"}], (car) => defaultPrint(car.brand))
myForEach([{name: "N64", arch: "MIPS"}, {name: "3DS", arch: "ARM9"}], (console) => defaultPrint(`${item.name}${item.arch}`))
// in fact we could even use `Array.prototype.forEach` function and avoid the duplication with `myForEach`
// (which does basically what forEach does)
// var forEach = Array.prototype.forEach
// forEach.call([{name: "Tomba!"},{name: "NeoCortex"}], (person) => defaultPrint(person.name))

view raw
cleaner.js
hosted with ❤ by GitHub

 

I said naming is important but when you make something very generic you should also make the abstract names not tied to any concrete concept. In fact,¬†in Haskell (let’s pretend I know Haskell)¬†when a¬†concrete type of something may vary we use single letters to take their place.

function makelist(x) {return [x]}
makelist(document.head[0])
makelist("DKC:TF")
makelist("6502")
makelist(0xf13e455d7a1b96cd2d930e578284d889)

Bonus round

  1. Make your units of execution to perform a single task.
  2. Use dispatch/pattern matching/protocol something instead of conditionals.
  3. Enforce DRY as much as you can.