2

我改编了 DrBoolean 的镜头实现,这样它就可以在没有自省/鸭子打字/依赖原型身份的情况下工作。计算应完全由高阶函数的延续和函数参数确定。我已经走到了这一步:

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
);

在这个版本中,函子约束constMap在镜头构造函数中被硬编码。当view调用一个镜头时,$$(runConst, fx(Const))已经传递了正确的类型(),但是为了获得一个临时多态镜头,我也需要传递相应的函子实例。

我已经尝试了最明显的方法$$(runConst, fx(constMap) (Const)),但是,这会干扰构图。我就是想不通。

4

0 回答 0