将相同的参数应用于函数列表,并在每个结果之间进行操作

Apply same argument to list of functions, and do an operation between each result

我有一个函数列表,每个函数都采用相同的参数,return 一个数字。我想对每个函数应用一个参数,并对每个连续结果执行一个操作(在本例中为减法):

    const run = item => buyPrice(item) -
                        sellPrice(item) -
                        receivingCost(item);

是否有一种干净、无意义的方法来创建此函数?

使用Array.prototype.map()调用列表中的所有函数,然后Array.prototype.reduce()进行所有减法:

function run (item) {
    const funcs = [buyPrice, sellPrice, receivingCost];
    return funcs.map(f => f(item)).reduce((x, y) => x - y);
}

我不是很清楚你到底在问什么,但这就是你要找的吗?这个想法是将您的函数保存在一个数组中,然后使用 R.reduce() 减去给定项的每个函数调用的结果。

EDIT - 更新代码以通过使用函数组合更严格地遵守 Pointfree 标准。

const reduce = R.reduce;
const curry = R.curry;
const juxt = R.juxt;
const isNil = R.isNil;
var item = {
    buyPrice: 5,
    sellPrice: 8,
    receivingCost: 1
};

const getBuyPrice = R.prop("buyPrice");
const getSellPrice = R.prop("sellPrice");
const getReceivingCost = R.prop("receivingCost");

const fns = [getBuyPrice, getSellPrice, getReceivingCost];
const getItemPrices = juxt(fns);
const subtract = curry((a, b) => isNil(a) ? b : a - b);
const subtractArr = reduce(subtract);
const subtractArrFromFirstValue = subtractArr(null);
const run = R.compose(subtractArrFromFirstValue, getItemPrices);

console.log(run(item));
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.24.1/ramda.min.js"></script>

这并非完全没有意义,但我认为它解决了某些复杂问题:

const run = lift((b, s, r) => b - s - r)(buyPrice, sellPrice, receivingCost)

虽然我确定我们可以创建 (b, s, r) => b - s - r 的无点版本,但我真的怀疑我们能否找到一个具有表现力的版本。

您可以在 Ramda REPL.

上看到实际效果