使用 Sanctuary.js 合并多个对象

Merge multiple objects with Sanctuary.js

我正在尝试将多个对象与 Sanctuary 合并。

使用 Ramda.js 我会做这样的事情(参见 REPL here):

const R = require('ramda');
const initialEntry = { a: 0, b: 1 };
const entries = [{c: 2}, {d: 3, e: 4}, {f: 5, g: 6, h: 7}];
R.reduce(Object.assign, initialEntry, entries);

但是,对于 Santuary.js,以下代码行会引发异常。

S.reduce(Object.assign)(initialEntry)(entries)

这是我得到的异常:

! Invalid value

reduce :: Foldable f => (a -> b -> a) -> a -> f b -> a
                              ^^^^^^
                                1

1)  {"a": 0, "b": 1} :: Object, StrMap Number, StrMap FiniteNumber, StrMap Integer, StrMap NonNegativeInteger, StrMap ValidNumber

The value at position 1 is not a member of ‘b -> a’.

我对这个错误信息感到困惑。我使用 S.reduce 不正确吗?另外,如果我写 S.reduce(Object.assign)(initialEntry)([]).

也不会出错

这是因为 reduce 的第一个参数采用签名为 a -> b -> a 的函数。与 Ramda 不同,Sanctuary 对此类签名非常严格。您必须为它提供一个接受一种类型参数的函数和 returns 一个接受第二种类型参数的函数和 returns 第一种类型参数的函数。 Object assign 不会那样做。一次性获取可变数量的对象。

您可以通过将 Object.assign 替换为 a => b => Object.assign(a, b) 来解决此问题:

const initialEntry = { a: 0, b: 1 };
const entries = [{c: 2}, {d: 3, e: 4}, {f: 5, g: 6, h: 7}];

const res = S.reduce(a => b => Object.assign(a, b)) (initialEntry) (entries);

console.log(res);
<script src="https://bundle.run/sanctuary@1.0.0"></script>
<script>const S = sanctuary</script>

Ramda 版本可以工作,因为它需要一个二进制函数 reduce。虽然 Object.assign 在技术上是可变的,但如果将其视为二元函数,则一切正常。

<a href="https://sanctuary.js.org/#concat" rel="nofollow noreferrer">S.concat</a> can be specialized to <a href="https://github.com/sanctuary-js/sanctuary-def#StrMap" rel="nofollow noreferrer">StrMap</a> a -> <a href="https://github.com/sanctuary-js/sanctuary-def#StrMap" rel="nofollow noreferrer">StrMap</a> a -> <a href="https://github.com/sanctuary-js/sanctuary-def#StrMap" rel="nofollow noreferrer">StrMap</a> a. As a result, the type of <a href="https://sanctuary.js.org/#reduce" rel="nofollow noreferrer">S.reduce</a> (<a href="https://sanctuary.js.org/#concat" rel="nofollow noreferrer">S.concat</a>) ({}) is <a href="https://github.com/sanctuary-js/sanctuary-type-classes#Foldable" rel="nofollow noreferrer">Foldable</a> f => f (<a href="https://github.com/sanctuary-js/sanctuary-def#StrMap" rel="nofollow noreferrer">StrMap</a> a) -> <a href="https://github.com/sanctuary-js/sanctuary-def#StrMap" rel="nofollow noreferrer">StrMap</a> a. This can be specialized to <a href="https://github.com/sanctuary-js/sanctuary-def#Array" rel="nofollow noreferrer">Array</a> (<a href="https://github.com/sanctuary-js/sanctuary-def#StrMap" rel="nofollow noreferrer">StrMap</a> a) -> <a href="https://github.com/sanctuary-js/sanctuary-def#StrMap" rel="nofollow noreferrer">StrMap</a>一个。例如:

> S.reduce (S.concat) ({}) ([{a: 0, b: 1}, {c: 2}, {d: 3, e: 4}, {f: 5, g: 6, h: 7}])
{a: 0, b: 1, c: 2, d: 3, e: 4, f: 5, g: 6, h: 7}

避难所不提供合并任意个对象的功能。