概述
函数reduce()
使用列表中的所有元素依次进行某种运算,即先用初始值和第一个元素进行运算,再使用得到的结果和第二个元素进行相同的运算,依此类推直至列表的最后一个元素。
函数
reduce()
的迭代方式类似于大部分编程语言中的for循环语句,但迭代次数没有暴露出来。
参数:reduce(<result> = <init>, <element> in <list> | <expression>)
<result>
:初始值和每次向后面的元素传递运算结果的变量名<init>
:初始值<element>
:列表元素变量名<list>
:列表的别名<expression>
:运算表达式
返回值:
- 最终的运算结果
一般用法
本例将列表[1,2,3]中的数字求和:
with [1,2,3] as list
return reduce(sum = 0, element in list | sum + element)
6
示例图集:

在一个空图集中,依次运行以下各行语句创建示例图集:
create().node_schema("firm").node_schema("human").edge_schema("hold")
create().edge_property(@hold, "portion", double)
insert().into(@firm).nodes([{_id:"F001", _uuid:1}, {_id:"F002", _uuid:2}])
insert().into(@human).nodes([{_id:"H001", _uuid:3}, {_id:"H002", _uuid:4}])
insert().into(@hold).edges([{_uuid:1, _from_uuid:3, _to_uuid:1, portion:0.3}, {_uuid:2, _from_uuid:2, _to_uuid:1, portion:0.7}, {_uuid:3, _from_uuid:3, _to_uuid:2, portion:0.4}, {_uuid:4, _from_uuid:4, _to_uuid:2, portion:0.6}])
本例计算公司F001的各个最终受益人的持股份额:
n({_id == "F001"}).le()[:5].n({@human} as UBO) as p
with pedges(p) as edgeList
call{
with edgeList
uncollect edgeList as edges
with collect(edges.portion) as portionList
return reduce(init = 1, element in portionList | init * element) as share
}
group by UBO
return table(UBO._id, sum(share))
| UBO._id | sum(share) |
|---------|------------|
| H001 | 0.58 |
| H002 | 0.42 |