# reduce() function¶

This topic will describe the reduce function.

## OpenCypher Compatibility¶

In openCypher, the reduce() function is not defined. nGQL will implement the reduce() function in the Cypher way.

## Syntax¶

The reduce() function applies an expression to each element in a list one by one, chains the result to the next iteration by taking it as the initial value, and returns the final result. This function iterates each element e in the given list, runs the expression on e, accumulates the result with the initial value, and store the new result in the accumulator as the initial value of the next iteration. It works like the fold or reduce method in functional languages such as Lisp and Scala.

reduce(<accumulator> = <initial>, <variable> IN <list> | <expression>)

Parameter Description
accumulator A variable that will hold the accumulated results as the list is iterated.
initial An expression that runs once to give an initial value to the accumulator.
variable A variable in the list that will be applied to the expression successively.
list A list or a list of expressions.
expression This expression will be run on each element in the list once and store the result value in the accumulator.

Note

The type of the value returned depends on the parameters provided, along with the semantics of the expression.

## Examples¶

nebula> RETURN reduce(totalNum = 10, n IN range(1, 3) | totalNum + n) AS r;
+----+
| r  |
+----+
| 16 |
+----+

nebula> RETURN reduce(totalNum = -4 * 5, n IN [1, 2] | totalNum + n * 2) AS r;
+-----+
| r   |
+-----+
| -14 |
+-----+

nebula> MATCH p = (n:player{name:"LeBron James"})<-[:follow]-(m) \
RETURN  nodes(p)[0].age AS src1,  nodes(p)[1].age AS dst2,  \
reduce(totalAge = 100, n IN nodes(p) | totalAge + n.age) AS sum;
+------+------+-----+
| src1 | dst2 | sum |
+------+------+-----+
| 34   | 31   | 165 |
+------+------+-----+
| 34   | 29   | 163 |
+------+------+-----+
| 34   | 33   | 167 |
+------+------+-----+
| 34   | 26   | 160 |
+------+------+-----+
| 34   | 34   | 168 |
+------+------+-----+
| 34   | 37   | 171 |
+------+------+-----+

nebula> LOOKUP ON player WHERE player.name == "Tony Parker" \
|  GO FROM $-.VertexID over follow \ WHERE follow.degree != reduce(totalNum = 5, n IN range(1, 3) | $$.player.age + totalNum + n) \ YIELD$$.player.name AS id,$\$.player.age AS age, follow.degree AS degree;
+---------------------+-----+--------+
| id                  | age | degree |
+---------------------+-----+--------+
| "Tim Duncan"        | 42  | 95     |
+---------------------+-----+--------+
| "LaMarcus Aldridge" | 33  | 90     |
+---------------------+-----+--------+
| "Manu Ginobili"     | 41  | 95     |
+---------------------+-----+--------+


Last update: July 19, 2021