1 |
1875
|
aaronmk
|
# Data structures
|
2 |
|
|
|
3 |
1884
|
aaronmk
|
import lists
|
4 |
|
|
import util
|
5 |
1882
|
aaronmk
|
|
6 |
1884
|
aaronmk
|
def rmap(func, value, levels=None):
|
7 |
|
|
'''Recursively applies func to all members of value
|
8 |
|
|
@param func(value, is_leaf):value
|
9 |
|
|
'''
|
10 |
|
|
expand = util.coalesce(levels, 1) > 0 and (lists.is_seq(value)
|
11 |
|
|
or isinstance(value, dict)) # whether value would be expanded
|
12 |
|
|
value = func(value, not expand)
|
13 |
|
|
|
14 |
|
|
if expand: # does nothing if func() returned a type that won't be expanded
|
15 |
|
|
levels = util.do_ignore_none(lambda v: v-1, levels)
|
16 |
|
|
rmap_ = lambda v: rmap(func, v, levels)
|
17 |
|
|
if lists.is_seq(value): value = map(rmap_, value)
|
18 |
|
|
elif isinstance(value, dict):
|
19 |
|
|
value = dict(((k, rmap_(v)) for k, v in value.iteritems()))
|
20 |
|
|
|
21 |
|
|
return value
|