Skip to content

Commit 0b59029

Browse files
matthewleonpaf31
authored andcommitted
Indexed foldable-traversable instances (#23)
* FunctorWithIndex implementation Resolves #21 * FoldableWithIndex instance * TraversableWithIndex instance * Modify indexed instances to use Maybe index.
1 parent 1e1111e commit 0b59029

File tree

1 file changed

+22
-1
lines changed

1 file changed

+22
-1
lines changed

src/Data/NonEmpty.purs

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,14 @@ import Prelude
1818
import Control.Alt ((<|>))
1919
import Control.Alternative (class Alternative)
2020
import Control.Plus (class Plus, empty)
21-
2221
import Data.Eq (class Eq1, eq1)
2322
import Data.Foldable (class Foldable, foldl, foldr, foldMap)
23+
import Data.FoldableWithIndex (class FoldableWithIndex, foldMapWithIndex, foldlWithIndex, foldrWithIndex)
24+
import Data.FunctorWithIndex (class FunctorWithIndex, mapWithIndex)
25+
import Data.Maybe (Maybe(..))
2426
import Data.Ord (class Ord1, compare1)
2527
import Data.Traversable (class Traversable, traverse, sequence)
28+
import Data.TraversableWithIndex (class TraversableWithIndex, traverseWithIndex)
2629

2730
-- | A non-empty container of elements of type a.
2831
-- |
@@ -88,11 +91,29 @@ instance ord1NonEmpty :: Ord1 f => Ord1 (NonEmpty f) where
8891
instance functorNonEmpty :: Functor f => Functor (NonEmpty f) where
8992
map f (a :| fa) = f a :| map f fa
9093

94+
instance functorWithIndex
95+
:: FunctorWithIndex i f
96+
=> FunctorWithIndex (Maybe i) (NonEmpty f) where
97+
mapWithIndex f (a :| fa) = f Nothing a :| mapWithIndex (f <<< Just) fa
98+
9199
instance foldableNonEmpty :: Foldable f => Foldable (NonEmpty f) where
92100
foldMap f (a :| fa) = f a <> foldMap f fa
93101
foldl f b (a :| fa) = foldl f (f b a) fa
94102
foldr f b (a :| fa) = f a (foldr f b fa)
95103

104+
instance foldableWithIndexNonEmpty
105+
:: (FoldableWithIndex i f)
106+
=> FoldableWithIndex (Maybe i) (NonEmpty f) where
107+
foldMapWithIndex f (a :| fa) = f Nothing a <> foldMapWithIndex (f <<< Just) fa
108+
foldlWithIndex f b (a :| fa) = foldlWithIndex (f <<< Just) (f Nothing b a) fa
109+
foldrWithIndex f b (a :| fa) = f Nothing a (foldrWithIndex (f <<< Just) b fa)
110+
96111
instance traversableNonEmpty :: Traversable f => Traversable (NonEmpty f) where
97112
sequence (a :| fa) = NonEmpty <$> a <*> sequence fa
98113
traverse f (a :| fa) = NonEmpty <$> f a <*> traverse f fa
114+
115+
instance traversableWithIndexNonEmpty
116+
:: (TraversableWithIndex i f)
117+
=> TraversableWithIndex (Maybe i) (NonEmpty f) where
118+
traverseWithIndex f (a :| fa) =
119+
NonEmpty <$> f Nothing a <*> traverseWithIndex (f <<< Just) fa

0 commit comments

Comments
 (0)