generic-ify treereduce
authorLuke Kenneth Casson Leighton <lkcl@lkcl.net>
Tue, 26 May 2020 12:43:36 +0000 (13:43 +0100)
committerLuke Kenneth Casson Leighton <lkcl@lkcl.net>
Tue, 26 May 2020 12:43:36 +0000 (13:43 +0100)
src/nmutil/util.py

index 28a8e13621fef0efb454f3624a8b4adf2942f275..3c708bdfe204bd2614b8d30defcc08a44baf0691 100644 (file)
@@ -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))