|
|
|
|
|
by dllthomas
3399 days ago
|
|
Don't overthink it. But if we're gonna overthink it, one thing we can notice is that a rose tree is a free monad, and like any free structure is initial in its category - meaning there's a unique monad homomorphism from a rose tree to any other monad. Lists form a monad, so we can ask "what is that homomorphism?" It turns out to be the traditional definition of flatten. That is to say, only flatten solves these equations for lists and rose trees: (flatten . f =<< flatten m) == flatten (f =<< m)
pure x = flatten (pure x)
|
|
I'm not sure what you think is so simple about your solution compared to:
Goodness, and Perl gets a bad reputation for the amount of punctuation in the code.Of course if you want flatten in Haskell you have it for Tree and Forest.
If a Perl programmer wanted to pull in a CPAN module, there are many from which to choose. Of course, it was just done in a one-line subroutine...:http://search.cpan.org/~obradovic/List-Flatten-0.01/lib/List... (which does not handle arbitrary depths)
http://search.cpan.org/~rthompson/List-Flatten-Recursive-0.1... (which seems overly complicated)
http://search.cpan.org/~rsavage/Set-Array-0.30/lib/Set/Array... (which tries to flatten hashes as well as lists and seems, well, overly complicated... and pulls in a bunch more methods and functions)
http://search.cpan.org/~satoh/List-Enumerator-0.10/ (which seems about right, including stopping the flattening at an arbitrary depth and comes with other useful array tools)
Of course it's possible to apply the concept of flattening to hashes/dictionaries, too, so there goes the concept of keeping the original sort order.
http://search.cpan.org/~bbc/Hash-Flatten-1.19/lib/Hash/Flatt...
http://search.cpan.org/~chocolate/Hash-Fold-0.1.2/lib/Hash/F...