Skip to content

Commit 12fdaf1

Browse files
authored
Merge pull request #89 from matthewleon/foldable1-intercalate
Foldable1.intercalate
2 parents 468948e + 5c28cc4 commit 12fdaf1

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

src/Data/Semigroup/Foldable.purs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,12 @@ module Data.Semigroup.Foldable
77
, sequence1_
88
, foldMap1Default
99
, fold1Default
10+
, intercalate
11+
, intercalateMap
1012
) where
1113

1214
import Prelude
15+
1316
import Data.Foldable (class Foldable)
1417
import Data.Monoid.Dual (Dual(..))
1518
import Data.Monoid.Multiplicative (Multiplicative(..))
@@ -80,3 +83,27 @@ maximum = ala Max foldMap1
8083

8184
minimum :: forall f a. Ord a => Foldable1 f => f a -> a
8285
minimum = ala Min foldMap1
86+
87+
-- | Internal. Used by intercalation functions.
88+
newtype JoinWith a = JoinWith (a -> a)
89+
90+
joinee :: forall a. JoinWith a -> a -> a
91+
joinee (JoinWith x) = x
92+
93+
instance semigroupJoinWith :: Semigroup a => Semigroup (JoinWith a) where
94+
append (JoinWith a) (JoinWith b) = JoinWith $ \j -> a j <> j <> b j
95+
96+
-- | Fold a data structure using a `Semigroup` instance,
97+
-- | combining adjacent elements using the specified separator.
98+
intercalate :: forall f m. Foldable1 f => Semigroup m => m -> f m -> m
99+
intercalate = flip intercalateMap id
100+
101+
-- | Fold a data structure, accumulating values in some `Semigroup`,
102+
-- | combining adjacent elements using the specified separator.
103+
intercalateMap
104+
:: forall f m a
105+
. Foldable1 f
106+
=> Semigroup m
107+
=> m -> (a -> m) -> f a -> m
108+
intercalateMap j f foldable =
109+
joinee (foldMap1 (JoinWith <<< const <<< f) foldable) j

0 commit comments

Comments
 (0)