函数 reduce() 可以对列表中的所有元素依次迭代进行某种运算,即使用初始值和第一个元素进行运算,再使用得到的运算结果和第二个元素进行运算,以此类推直至列表结束。
该函数的迭代方式类似于大部分编程语言中的 for 语句,但迭代次数没有暴露出来。
语法:
reduce(<result> = <initial_value>, <element> in <list> | <expression>)
- <result> 为运算结果的变量名
- <initial_value> 为初始值
- <element> 为列表元素的变量名
- <list> 为列表的别名
- <expression> 为运算表达式
一般用法
示例:将列表 [1,2,3,4] 中的数字求和
with [1,2,3] as list
return reduce(sum = 0, element in list | sum + element) as mySum
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 |