Skip to content

Instantly share code, notes, and snippets.

@robrix
Created September 2, 2016 15:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robrix/7e20d7d85ecbde1b37ef1a8f6c0a94a2 to your computer and use it in GitHub Desktop.
Save robrix/7e20d7d85ecbde1b37ef1a8f6c0a94a2 to your computer and use it in GitHub Desktop.
Joining a foldable collection of Monoids by some separator element.
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)
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