Skip to content

Instantly share code, notes, and snippets.

@tel
Created June 20, 2015 05:06
Show Gist options
  • Save tel/ef6e4c3d936142b493a9 to your computer and use it in GitHub Desktop.
Save tel/ef6e4c3d936142b493a9 to your computer and use it in GitHub Desktop.
Really simple van Laarhoven lenses in Javascript
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