Created
June 20, 2015 05:06
-
-
Save tel/ef6e4c3d936142b493a9 to your computer and use it in GitHub Desktop.
Really simple van Laarhoven lenses in Javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const IdModule = { | |
fmap: (fn) => (x) => fn(x), | |
} | |
const ConstModule = { | |
fmap: (fn) => (x) => x, | |
} | |
/** | |
* Construct a lens from a getter and a setter | |
* | |
* @param get {S -> A} | |
* @param set {A -> (S -> S)} | |
*/ | |
const lens = (get) => (set) => (mod) => (inj) => (s) => | |
mod.fmap((a) => set(a)(s))(inj(get(s))); | |
/** | |
* View a lens as a getter. | |
* | |
* @param lens | |
* @param s - the "whole" value | |
*/ | |
const get = (lens) => (s) => // we can eta expand this def if needed | |
lens(ConstModule)((a) => a)(s) | |
/** | |
* View a lens as a setter. | |
* | |
* @param lens | |
* @param fn {A -> B} | |
* @param s - the whole value | |
*/ | |
const set = (lens) => (fn) => (s) => // we can eta expand this def if needed | |
lens(IdModule)(fn)(s) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment