【发布时间】:2019-01-16 02:56:51
【问题描述】:
我正在尝试编写返回镜头的函数,以生产新镜头,并以无点风格进行。
这可能是一个关于函数组合的更普遍的问题。镜头只是一个案例研究。我对镜头不感兴趣,但我想知道如何以无点方式组合这些功能的一般模式。
const obj = {a: {x: 0}, b: {x: 42}};
// this won't work, but I want it to work
const pointFreeComposedLens = R.compose(R.lensProp, R.lensProp('x'));
R.view(pointFreeComposedLens('a'), obj); // returns 'undefined'
// this works
const pointyComposedLens = key => R.compose(R.lensProp(key), R.lensProp('x'));
R.view(pointyComposedLens('a'), obj); // returns '0'
组合函数的模式是什么,这样我就不需要为组合管道中的第一个函数重写参数?
举一个令人震惊的例子:
const deepLens = (a, b, c) => R.lensPath([a, b, c]);
// This works, but is tedious & verbose
const extraDeep = (a, b, c, x) => R.compose(deepLens(a,b,c), R.lensProp(x));
const gammaDeep = (a, b, c, y) => R.compose(deepLens(a,b,c), R.lensProp(y));
// Doesn't work, but it would be nicer to write:
const extraDeep = x => R.compose(deepLens, R.lensProp(x));
// and call it like so:
R.view(extraDeep('a','b','c','x'), obj);
【问题讨论】:
-
我认为镜头是开始学习构图的错误类型,因为它们可以说代表“高阶构图”,这意味着特定于镜头的构图(
view,set,over),它采用另一个组合来编码您要查找的路径。
标签: javascript functional-programming ramda.js