使用Sanctuary.js合并多个对象

问题描述 投票:0回答:2

我试图将多个对象与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)([]),我没有错误。

javascript functional-programming ramda.js sanctuary
2个回答
3
投票

这是因为reduce的第一个参数采用了签名a -> b -> a的函数。与Ramda不同,Sanctuary严格遵守此类签名。您必须为它提供一个函数,该函数接受一种类型的参数并返回一个函数,该函数接受第二种类型的参数并返回第一种类型的参数。 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/[email protected]"></script>
<script>const S = sanctuary</script>

Ramda版本有效,因为它需要reduce的二进制函数。虽然Object.assign在技术上是可变的,但如果你把它当成二元函数,那么一切正常。


1
投票

S.concat可以专门为StrMap a -> StrMap a -> StrMap a。因此,S.reduce (S.concat) ({})的类型是Foldable f => f (StrMap a) -> StrMap a。这可以专门针对Array (StrMap a) -> 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}

Sanctuary不提供合并任意对象的功能。

© www.soinside.com 2019 - 2024. All rights reserved.