How to create a purely functional ad-hoc polymorphic lens without any introspection?

117 views Asked by At

I adapted DrBoolean's lens implementation, so that it works without introspection/duck typing/relying on prototype identities. The computation should be exclusively determined by continuations and function arguments of higher order functions. I've come this far:

const id = x => x;

// compose n functions (right to left)
const $$ = (f, ...fs) => x =>
  fs.length === 0
    ? f(x)
    : f($$(...fs) (x));

// function encoded Const type
const Const = x => k => k(x);
const constMap = f => fx => fx(x => Const(x));
const runConst = fx => fx(id);

// lens constructor
const objLens = k => cons => o =>
  constMap(v => Object.assign({}, o, {[k]: v})) (cons(o[k]));

const arrLens = i => cons => xs =>
  constMap(v => Object.assign([], xs, {[i]: v})) (cons(xs[i]));

const view = fx =>
  $$(runConst, fx(Const));

const user = {name: "Bob", addresses: [
  {street: '99 Maple', zip: 94004, type: 'home'},
  {street: '2000 Sunset Blvd', zip: 90069, type: 'work'}]};

// a lens
const sndStreetLens =
  $$(objLens("addresses"), arrLens(1), objLens("street"));

console.log(
  view(sndStreetLens) (user) // 2000 Sunset Blvd
);

In this version the functor constraint constMap is hard coded in the lens constructor. When view invokes a lens, the right type ($$(runConst, fx(Const))) is already passed, but in order to obtain an ad-hoc polymorphic lense, I need to pass the corresponding functor instance too.

I already tried the most obvious thing $$(runConst, fx(constMap) (Const)), however, this interferes with the composition. I just can't figure it out.

0

There are 0 answers