gpt4 book ai didi

javascript - 使用 Ramda,你如何针对二进制函数进行组合?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:10:42 25 4
gpt4 key购买 nike

Ramda 通过 R.equals 提供区分大小写的等号,但是我想要一个不区分大小写的等号测试。 Ramda 也提供了R.compose,但是在 Ramda 组合中,它假定最左边的参数是一元的。

我想做的是类似

R.compose( R.equals(...), R.toLower )

但是,我想在二进制函数 R.equals 上编写 R.toLower 吗?

有没有办法做到这一点?类型喜欢

(b->b->c) -> (a->b) => (a->a->c)

我想要的是类似于 Haskell 的 Data.Function.on定义为

on b u x y runs the binary function b on the results of applying unary function u to two arguments x and y. From the opposite perspective, it transforms two inputs and combines the outputs.

最佳答案

编辑:R.useWith 非常接近您要查找的内容:

Accepts a function fn and a list of transformer functions and returns a new curried function. When the new function is invoked, it calls the function fn with parameters consisting of the result of calling each supplied handler on successive arguments to the new function.

所以你可以这样定义你的函数:

const equalsi = R.useWith(R.equals, [R.toLower, R.toLower]);

例子:

const equalsi = R.useWith(R.equals, [R.toLower, R.toLower]);

const check = (a, b) => console.log(`${a} = ${b}?`, equalsi(a, b));

check('aaa', 'aaa');
check('aaa', 'aa');
check('aAa', 'aaa');
check('aaa', 'aAa');
check('aba', 'aaa');
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.0/ramda.min.js"></script>

如果你想要一些与你提到的 Haskell on 函数等价的东西,你可以定义一个如下:

const on = (b, u) => R.useWith(b, [u, u]);
const equalsi = on(R.equals, R.toLower);

const check = (a, b) => console.log(`${a} = ${b}?`, equalsi(a, b));

check('aaa', 'aaa');
check('aaa', 'aa');
check('aAa', 'aaa');
check('aaa', 'aAa');
check('aba', 'aaa');
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.0/ramda.min.js"></script>


上一个答案:

可能有更优雅的方法来做到这一点,但这个有效:

const equalsi = R.unapply(R.compose(
R.apply(R.equals),
R.map(R.toLower)
));

分解:

// [] -> Boolean
// Takes an array of two strings and returns true if they are equal
R.apply(R.equals)

// [] -> Boolean
// Takes an array of two strings, converts them to lowercase, and returns true
// if those lowercase strings are equal
R.compose(R.apply(R.equals), R.map(R.toLower))

// String -> String -> Boolean
// Takes two strings, converts them to lowercase, and returns true if those lowercase
// string are equal
R.unapply(R.compose(R.apply(R.equals), R.map(R.toLower)));

您还可以根据 Ramda 函数定义 on 函数,然后使用它:

const on = (b, u) => R.unapply(R.compose(R.apply(b), R.map(u));

const equalsi = on(R.equals, R.toLower);

关于javascript - 使用 Ramda,你如何针对二进制函数进行组合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53492645/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com