Created
September 2, 2016 15:50
-
-
Save robrix/7e20d7d85ecbde1b37ef1a8f6c0a94a2 to your computer and use it in GitHub Desktop.
Joining a foldable collection of Monoids by some separator element.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Data.Maybe | |
import Data.Monoid | |
-- | Join a Foldable collection of Monoids by a separator element. | |
join :: (Monoid a, Foldable t) => a -> t a -> a | |
join sep = fromMaybe mempty . fst . foldr combine (Nothing, True) | |
where combine each (into, isFirst) = if isFirst | |
then (Just each, False) | |
else (Just each <> Just sep <> into, False) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
join ", " [] -- => "" | |
join ", " ["a"] -- => "a" | |
join ", " ["a", "b"] -- => "a, b" | |
join ", " ["a", "b", "c"] -- => "a, b, c" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment