如何创建无反省功能的纯功能临时多态镜片?

时间:2018-12-02 08:19:04

标签: javascript functional-programming lenses adhoc-polymorphism

我改编了DrBoolean的lens implementation,因此它不需要自省/鸭子输入/不依赖原型身份就可以工作。计算应仅由高阶函数的延续和函数自变量确定。我走了这么远:

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)),但是,这会干扰构图。我只是想不通。

0 个答案:

没有答案