访问 R.pipe 中的临时变量。拉姆达
Access temp variables in R.pipe. Ramda
假设我要计算平均成本:
const products = [
{
cost: 300
},
{
cost: 700
}
];
所以先提取成本属性,汇总它们,然后除以项目的数量。
const calcualteAveragePrice = R.pipe(
R.map(R.prop('cost') // [300, 700]
R.sum, // 1000
R.divide(??) // How do I divide with the number of items here??
)
在最后一步中,我需要除以项目数。由于它是免费的,我不能做 arr.length
。
Ramda 确实有一个 mean
function (as well as a median
。)所以这将使您的解决方案相当简单:
const calculateAveragePrice = compose (mean, pluck( 'cost'))
const products = [{cost: 300}, {cost: 700}]
console .log (
calculateAveragePrice(products)
)
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script>
<script>const {compose, mean, pluck} = R </script>
当然你也可以写成pipe (pluck('cost'), mean)
。我更喜欢 compose
用于单行,pipe
用于其他任何内容,但这只是一个品味问题。
但是如果您不知道 Ramda 提供了这个,您可以使用 converge
:
编写自己的无点 average
函数
const average = converge(divide, [sum, length])
converge
及其堂兄 useWith
are designed to make it easier to write point-free versions of code. I always include a warning that point-free should rarely be a goal on its own, however. It's useful only when it serves to improve the readability of the code. Both converge
and useWith
tend to be questionable on that score. There is an alternative that is more standard in the FP world: the function lift
:
const average = lift (divide) (sum, length)
lift
将接受特定类型值的函数转换为接受这些值的 containers 值的函数。由于 returns 给定类型的值的函数可以被视为容器(必要时斜视),lift (f) (g, h)
等同于 (x) => f (g (x), h (x))
。 (SO问题中有更多信息, 。)
converge
稍微灵活一些,但如果可以的话,我总是使用 lift
。感觉比较标准
假设我要计算平均成本:
const products = [
{
cost: 300
},
{
cost: 700
}
];
所以先提取成本属性,汇总它们,然后除以项目的数量。
const calcualteAveragePrice = R.pipe(
R.map(R.prop('cost') // [300, 700]
R.sum, // 1000
R.divide(??) // How do I divide with the number of items here??
)
在最后一步中,我需要除以项目数。由于它是免费的,我不能做 arr.length
。
Ramda 确实有一个 mean
function (as well as a median
。)所以这将使您的解决方案相当简单:
const calculateAveragePrice = compose (mean, pluck( 'cost'))
const products = [{cost: 300}, {cost: 700}]
console .log (
calculateAveragePrice(products)
)
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script>
<script>const {compose, mean, pluck} = R </script>
当然你也可以写成pipe (pluck('cost'), mean)
。我更喜欢 compose
用于单行,pipe
用于其他任何内容,但这只是一个品味问题。
但是如果您不知道 Ramda 提供了这个,您可以使用 converge
:
average
函数
const average = converge(divide, [sum, length])
converge
及其堂兄 useWith
are designed to make it easier to write point-free versions of code. I always include a warning that point-free should rarely be a goal on its own, however. It's useful only when it serves to improve the readability of the code. Both converge
and useWith
tend to be questionable on that score. There is an alternative that is more standard in the FP world: the function lift
:
const average = lift (divide) (sum, length)
lift
将接受特定类型值的函数转换为接受这些值的 containers 值的函数。由于 returns 给定类型的值的函数可以被视为容器(必要时斜视),lift (f) (g, h)
等同于 (x) => f (g (x), h (x))
。 (SO问题中有更多信息,
converge
稍微灵活一些,但如果可以的话,我总是使用 lift
。感觉比较标准