From: Luke Kenneth Casson Leighton Date: Tue, 26 May 2020 12:43:36 +0000 (+0100) Subject: generic-ify treereduce X-Git-Tag: 24jan2021_ls180~56 X-Git-Url: https://git.libre-soc.org/?a=commitdiff_plain;h=7a84a91fac7ec4faf143567c1f22c9d154a14d70;p=nmutil.git generic-ify treereduce --- 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))