Monads/Writer monad: Difference between revisions
m
→ES5
(→{{header|JavaScript}}: (added comments at two stages)) |
m (→ES5) |
||
Line 17:
<lang JavaScript>(function () {
'use strict';
// START WITH THREE SIMPLE FUNCTIONS
// Square root of a number more than 0
function root(x) {
return Math.sqrt(x);
}
// Add 1
function addOne(x) {
return x + 1;
}
// Divide by 2
function half(x) {
return x / 2;
}
// DERIVE LOGGING VERSIONS OF EACH FUNCTION
function loggingVersion(f, strLog) {
return function (v) {
Line 46:
}
}
var log_root = loggingVersion(root, "obtained square root"),
log_addOne = loggingVersion(addOne, "added 1"),
log_half = loggingVersion(half, "divided by 2");
// The Unit / Return function for the Writer monad:
// 'Lifts' a raw value into the wrapped form
Line 66:
};
}
// The Bind function for the Writer monad:
// applies a logging version of a function
// to the contents of a wrapped value
// and return a wrapped result (with extended log)
// Writer a -> (a -> Writer b) -> Writer b
function writerBind(w, f) {
var writerB = f(w.value);
return {
value: writerB.value,
Line 81:
};
}
// We can compose a chain of Writer functions (of any length) with a simple foldr/reduceRight
// which starts by 'lifting' the initial value into a Writer wrapping,
Line 93:
}, writerUnit(value));
}
var half_of_addOne_of_root = function (v) {
return logCompose(
Line 99:
);
};
return half_of_addOne_of_root(5);
})();</lang>
|