如何使用ramda的sequence
遍历字典?
给出下面的字典
cars = {color: ['yellow', 'red'], year: [2017], model: ['coup', 'sedan']}
我想产生遍历的结果
all_cars = [
{color: 'yellow', year: 2017, model: 'coup'},
{color: 'yellow', year: 2017, model: 'sedan'},
{color: 'red', year: 2017, model: 'coup'},
{color: 'red', year: 2017, model: 'sedan'}
]
使用R.sequence
会产生一个空列表的列表
R.sequence(R.of, cars)
[[]]
如果我遍历一个列表而不是字典,它会产生正确的笛卡尔乘积,但结果(当然)是列表而不是字典。
R.sequence(R.of, [['yellow', 'red'], [2017], ['coup', 'sedan']])
[["yellow", 2017, "coup"], ["yellow", 2017, "sedan"], ["red", 2017, "coup"], ["red", 2017, "sedan"]]
发布于 2017-11-15 03:52:15
我可以想到两种方法,一种涉及sequence
,另一种不涉及。
这个调用使用了上面的sequence(of)
调用:
const convert = lift(map)(
compose(zipObj, keys),
compose(sequence(of), values)
)
const all_cars = convert(cars);
另一个是由我常用的技术构建的,即通过一个接一个的转换来不断更改输出,直到我得到我想要的:
const combine = pipe(
toPairs,
map(apply(useWith(map, [objOf, identity]))),
reduce(xprod, [[]]),
map(flatten),
map(mergeAll)
)
const all_cars = combine(cars)
通过在多个列表中引入交叉积可能会使这一点更清楚:
const xproduct = reduce(pipe(xprod, map(unnest)), [[]])
const combine = pipe(
toPairs,
map(apply(useWith(map, [objOf, identity]))),
xproduct,
map(mergeAll)
)
第二个版本是我第一次尝试这个问题时想出来的。然后,当我查看您尝试过的内容时,我得到了第一个版本。第一个版本对我来说看起来更干净,尽管第二个版本中的大多数步骤都很琐碎。但由于其中有一个不是微不足道的步骤,第一个步骤似乎是总体上的赢家。
你可以在Ramda REPL上看到the first或the second。
https://stackoverflow.com/questions/47292623
复制相似问题