generic-ify treereduce
[nmutil.git] / src / nmutil / util.py
1 from collections.abc import Iterable
2
3 # XXX this already exists in nmigen._utils
4 # see https://bugs.libre-soc.org/show_bug.cgi?id=297
5 def flatten(v):
6 if isinstance(v, Iterable):
7 for i in v:
8 yield from flatten(i)
9 else:
10 yield v
11
12 # tree reduction function. operates recursively.
13 def treereduce(tree, op, fn):
14 """treereduce: apply a map-reduce to a list.
15 examples: OR-reduction of one member of a list of Records down to a
16 single data point:
17 treereduce(tree, operator.or_, lambda x: getattr(x, "data_o"))
18 """
19 #print ("treereduce", tree)
20 if not isinstance(tree, list):
21 return tree
22 if len(tree) == 1:
23 return fn(tree[0])
24 if len(tree) == 2:
25 return op(fn(tree[0]), fn(tree[1]))
26 s = len(tree) // 2 # splitpoint
27 return treereduce(op(tree[:s], op, fn), treereduce(tree[s:], op, fn))