Set consolidation: Difference between revisions

→‎Python: Added a functional version, expressed as fold, and using union in preference to mutation
m (→‎{{header|JavaScript}}: (pruned out one unused function))
(→‎Python: Added a functional version, expressed as fold, and using union in preference to mutation)
Line 1,889:
<pre>_test(consolidate) complete
_test(conso) complete</pre>
 
===Python: Functional===
{{Trans|Haskell}}
{{Trans|JavaScript}}
As a fold (catamorphism), using '''union''' in preference to mutation:
<lang python>from functools import (reduce)
 
 
# consolidated :: Ord a => [Set a] -> [Set a]
def consolidated(sets):
def go(xs, s):
if xs:
h = xs[0]
return go(xs[1:], h.union(s)) if (
h.intersection(s)
) else [h] + go(xs[1:], s)
else:
return [s]
return reduce(go, sets, [])
 
 
# TESTS ----------------------------------------------------
if __name__ == '__main__':
print(
*list(map(
lambda xs: consolidated(map(set, xs)),
[
['ab', 'cd'],
['ab', 'bd'],
['ab', 'cd', 'db'],
['hik', 'ab', 'cd', 'db', 'fgh']
]
)),
sep='\n'
)</lang>
{{Out}}
<pre>[{'b', 'a'}, {'c', 'd'}]
[{'b', 'a', 'd'}]
[{'a', 'd', 'b', 'c'}]
[{'a', 'd', 'b', 'c'}, {'k', 'h', 'f', 'i', 'g'}]</pre>
 
=={{header|Racket}}==
9,659

edits