Flatten a list: Difference between revisions

Content added Content deleted
Line 2,967: Line 2,967:
from itertools import (chain)
from itertools import (chain)



# ----------------------- FLATTEN ------------------------


# flatten :: NestedList a -> [a]
# flatten :: NestedList a -> [a]
def flatten(x):
def flatten(x):
'''A list of atomic values resulting from fully flattening
'''A list of atomic values resulting from fully
an arbitrarily nested list.'''
flattening an arbitrarily nested list.
'''
return concatMap(flatten)(x) if isinstance(x, list) else [x]
return concatMap(flatten)(x) if isinstance(x, list) else [x]




# ------------------------- TEST -------------------------
def main():
def main():
'''Test: flatten an arbitrarily nested list.'''
'''Test: flatten an arbitrarily nested list.
'''
print(
print(
fTable(__doc__ + ':')(showList)(showList)(
fTable(__doc__ + ':')(showList)(showList)(
Line 2,989: Line 2,994:




# GENERIC -------------------------------------------------
# ----------------------- GENERIC ------------------------


# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
Line 3,002: Line 3,007:
The list monad can be derived by using a function f which
The list monad can be derived by using a function f which
wraps its output in a list,
wraps its output in a list,
(using an empty list to represent computational failure).'''
(using an empty list to represent computational failure).
'''
return lambda xs: list(
chain.from_iterable(map(f, xs))
def go(xs):
return chain.from_iterable(map(f, xs))
)
return go




Line 3,040: Line 3,046:
[[1],[[2]],[[[3, 4]]]] -> [1,2,3,4]
[[1],[[2]],[[[3, 4]]]] -> [1,2,3,4]
[[1],2,[[3, 4], 5],[[[]]],[[[6]]],7,8,[]] -> [1,2,3,4,5,6,7,8]</pre>
[[1],2,[[3, 4], 5],[[[]]],[[[6]]],7,8,[]] -> [1,2,3,4,5,6,7,8]</pre>



===Functional Non-recursive===
===Functional Non-recursive===