Skip to content

Commit b66f2da

Browse files
committed
Foldable1 instance
convert fold1 and foldMap1 to instance methods
1 parent 23f2a37 commit b66f2da

File tree

1 file changed

+9
-10
lines changed

1 file changed

+9
-10
lines changed

src/Data/NonEmpty.purs

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,11 @@ module Data.NonEmpty
55
, singleton
66
, (:|)
77
, foldl1
8-
, foldMap1
9-
, fold1
108
, fromNonEmpty
119
, oneOf
1210
, head
1311
, tail
12+
, module Data.Semigroup.Foldable
1413
) where
1514

1615
import Prelude
@@ -24,6 +23,8 @@ import Data.FoldableWithIndex (class FoldableWithIndex, foldMapWithIndex, foldlW
2423
import Data.FunctorWithIndex (class FunctorWithIndex, mapWithIndex)
2524
import Data.Maybe (Maybe(..))
2625
import Data.Ord (class Ord1, compare1)
26+
import Data.Semigroup.Foldable (fold1, foldMap1)
27+
import Data.Semigroup.Foldable as SF
2728
import Data.Traversable (class Traversable, traverse, sequence)
2829
import Data.TraversableWithIndex (class TraversableWithIndex, traverseWithIndex)
2930

@@ -48,14 +49,6 @@ singleton a = a :| empty
4849
foldl1 :: forall f a. Foldable f => (a -> a -> a) -> NonEmpty f a -> a
4950
foldl1 f (a :| fa) = foldl f a fa
5051

51-
-- | Fold a non-empty structure, collecting results in a `Semigroup`.
52-
foldMap1 :: forall f a s. Semigroup s => Foldable f => (a -> s) -> NonEmpty f a -> s
53-
foldMap1 f (a :| fa) = foldl (\s a1 -> s <> f a1) (f a) fa
54-
55-
-- | Fold a non-empty structure.
56-
fold1 :: forall f s. Semigroup s => Foldable f => NonEmpty f s -> s
57-
fold1 = foldMap1 id
58-
5952
fromNonEmpty :: forall f a r. (a -> f a -> r) -> NonEmpty f a -> r
6053
fromNonEmpty f (a :| fa) = a `f` fa
6154

@@ -117,3 +110,9 @@ instance traversableWithIndexNonEmpty
117110
=> TraversableWithIndex (Maybe i) (NonEmpty f) where
118111
traverseWithIndex f (a :| fa) =
119112
NonEmpty <$> f Nothing a <*> traverseWithIndex (f <<< Just) fa
113+
114+
instance foldable1NonEmpty
115+
:: (Functor f, Foldable f)
116+
=> SF.Foldable1 (NonEmpty f) where
117+
fold1 (a :| fa) = foldl append a fa
118+
foldMap1 = SF.foldMap1Default

0 commit comments

Comments
 (0)