Array functions like map/reduce #436
Answered
by
stevenylai
patrickgalbraith
asked this question in
Q&A
-
I noticed that the new version supports arrays and structs. Just wondering if there is a way to implement array functions that can take a function/expression as an argument. Something along the lines of:
Or even something like this which I guess should be do-able as long as we can set the
|
Beta Was this translation helpful? Give feedback.
Answered by
stevenylai
Feb 22, 2024
Replies: 1 comment
-
Something like below should work @FunctionParameters({
@FunctionParameter(name = "array"),
@FunctionParameter(name = "placeholder", isLazy = true),
@FunctionParameter(name = "mapper", isLazy = true)
})
public class MapFunction extends AbstractFunction {
@Override
public EvaluationValue evaluate(
Expression expression, Token functionToken, EvaluationValue... parameterValues)
throws EvaluationException {
List<EvaluationValue> array = parameterValues[0].getArrayValue();
String placeHolder = parameterValues[1].getExpressionNode().getToken().getValue();
ASTNode mapper = parameterValues[2].getExpressionNode();
List<EvaluationValue> mapped = new ArrayList<>();
for (EvaluationValue value : array) {
mapped.add(expression.withValues(Map.of(placeHolder, value)).evaluateSubtree(mapper));
}
return EvaluationValue.arrayValue(mapped);
}
} Once added as a custom function, you should be able to write sth like: new Expression("MAP(products, quantity, total * quantity)")
.withValues(Map.<String, Object>of(
"products": List.of(1, 2, 3),
"total": 2
))
.evaluate(); |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
uklimaschewski
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Something like below should work