From 7a84a91fac7ec4faf143567c1f22c9d154a14d70 Mon Sep 17 00:00:00 2001 From: Luke Kenneth Casson Leighton Date: Tue, 26 May 2020 13:43:36 +0100 Subject: [PATCH] generic-ify treereduce --- src/nmutil/util.py | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/src/nmutil/util.py b/src/nmutil/util.py index 28a8e13..3c708bd 100644 --- a/src/nmutil/util.py +++ b/src/nmutil/util.py @@ -10,13 +10,18 @@ def flatten(v): yield v # tree reduction function. operates recursively. -def treereduce(tree, op, attr="data_o"): +def treereduce(tree, op, fn): + """treereduce: apply a map-reduce to a list. + examples: OR-reduction of one member of a list of Records down to a + single data point: + treereduce(tree, operator.or_, lambda x: getattr(x, "data_o")) + """ #print ("treereduce", tree) if not isinstance(tree, list): return tree if len(tree) == 1: - return getattr(tree[0], attr) + return fn(tree[0]) if len(tree) == 2: - return op(getattr(tree[0], attr), getattr(tree[1], attr)) + return op(fn(tree[0]), fn(tree[1])) s = len(tree) // 2 # splitpoint - return treereduce(op(tree[:s], op, attr), treereduce(tree[s:], op, attr)) + return treereduce(op(tree[:s], op, fn), treereduce(tree[s:], op, fn)) -- 2.30.2