// 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...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Fiddle Pages
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Get Fiddle Pages with PRO
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.