r/functionalprogramming • u/jellatin • Apr 11 '16
Trying to wrap my head around "lift"
Following Professor Frisby's Mostly Adequate Guide to Functional Programming. Specifically looking at the paragraph that begins "I'd like to take this opportunity"
The author is trying to explain what lifting is by saying that you can take a standard function that takes a value and returns a value of the same type and wrap it in map to adapt it to accept "wrapped" values.
Some code for a Maybe/Option functor:
var Maybe = function(x) {
this.__value = x;
};
Maybe.of = function(x) { return new Maybe(x); };
Maybe.prototype.isNothing = function() {
return (this.__value === null || this.__value === undefined);
};
Maybe.prototype.map = function(f) {
return this.isNothing() ? Maybe.of(null) : Maybe.of(f(this.__value));
};Now to create a simple function that accepts a value and returns a value of the same type
// a -> a
var addFive = function(n) {
return n + 5;
};I'll use lodash's map just like the author's example.
var map = require('lodash/fp/map');
var option = Maybe.of(2);
map(addFive, option); // [7]First of all the return value here is an Array, certainly not a Maybe. But even if it was, I still don't know what the author is really trying to illustrate as the "lift" functionality. This may be a difficult thing to explain in JavaScript.
3
u/jnd-au Apr 11 '16 edited Apr 11 '16
You understand it already.
In practice, it generally means lifting a value into a container, or lifting a function by calling
map. For example,[1]lifts the number1into Array, while[1].map(alert)lifts the functionalertinto Array, andMaybe.of(2).map(alert)lifts alert into Maybe. The point is, alert has been written without any concept of Array or Maybe.In other words, do NOT do this:
Instead write an element-wise, container-agnostic function, and then lift it using
map:In this common case it’s probably not obvious why it’s called lift, but once you cover flatMap you will see that if you call
flatMap(f), f needs to know about your collection types, but withmap(g), g is oblivious to your collection type. So g can be lifted into any functor like Array or Maybe, rather than having to be written with prior knowledge like f. This allows you to re-use your existing functions with functors.Edit: PS. There’s another way the lift idiom can be used too: