Ailrun / typed-f

Typed functional programming utilities
MIT License
20 stars 2 forks source link

[lens] Make Lens API composable #38

Open Ailrun opened 6 years ago

Ailrun commented 6 years ago

Description

Current lens API is not that composable. For example, in following code, you should pass whole nameLens.set()(target)('new name') to ageLens, to set both of them.

interface Target {
  name: string;
  age: number;
}

const targetLensG = new LensGenerator<Target>();
const nameLens = targetLensG.fromKey('name');
const ageLens = targetLensG.fromKey('age');

const setNameAndAge = (target) => ageLens.set()(nameLens.set()(target)('new name'))(24);

This is not ideal to compose. With following APIs, we can use more composable lens.

get(this: Lens<A, S, B, T>): Fun<[S], A>;
set(this: Lens<A, S, B, T>): Fun<[B], Fun<[S], T>>;
map(this: Lens<A, S, B, T>): Fun<[Fun<[A], B>], Fun<[S], T>>;

For above case,

interface Target {
  name: string;
  age: number;
}

const targetLensG = new LensGenerator<Target>();
const nameLens = targetLensG.fromKey('name');
const ageLens = targetLensG.fromKey('age');

const setNameAndAge = compose(
  ageLens.set()(24),
  nameLens.set()('new name'),
);