1
1
-- | This module defines a generic non-empty data structure, which adds an additional
2
2
-- | element to any container type.
3
3
4
- module Data.NonEmpty
4
+ module Data.NonEmpty
5
5
( NonEmpty (..)
6
6
, (:|)
7
7
, foldl1
8
8
, foldMap1
9
9
, fold1
10
+ , fromNonEmpty
11
+ , oneOf
10
12
) where
11
13
12
14
import Prelude
13
15
14
- import Data.Foldable
15
- import Data.Traversable
16
+ import Control.Alternative (Alternative )
17
+ import Control.Alt ((<|>))
18
+
19
+ import Data.Foldable (Foldable , foldl , foldr , foldMap )
20
+ import Data.Traversable (Traversable , traverse , sequence )
16
21
17
22
-- | A non-empty container of elements of type a.
18
23
-- |
@@ -34,34 +39,40 @@ infix 5 :|
34
39
foldl1 :: forall f a s . (Foldable f ) => (a -> a -> a ) -> NonEmpty f a -> a
35
40
foldl1 f (NonEmpty a fa) = foldl f a fa
36
41
37
- -- | Fold a non-empty structure, collecting results in a `Semigroup`.
42
+ -- | Fold a non-empty structure, collecting results in a `Semigroup`.
38
43
foldMap1 :: forall f a s . (Semigroup s , Foldable f ) => (a -> s ) -> NonEmpty f a -> s
39
44
foldMap1 f (NonEmpty a fa) = foldl (\s a1 -> s <> f a1) (f a) fa
40
45
41
46
-- | Fold a non-empty structure.
42
47
fold1 :: forall f s . (Semigroup s , Foldable f ) => NonEmpty f s -> s
43
48
fold1 = foldMap1 id
44
49
50
+ fromNonEmpty :: forall f a r . (a -> f a -> r ) -> NonEmpty f a -> r
51
+ fromNonEmpty f (NonEmpty a fa) = a `f` fa
52
+
53
+ oneOf :: forall f a . (Alternative f ) => NonEmpty f a -> f a
54
+ oneOf (NonEmpty a fa) = pure a <|> fa
55
+
45
56
instance showNonEmpty :: (Show a , Show (f a )) => Show (NonEmpty f a ) where
46
57
show (NonEmpty a fa) = " (NonEmpty " ++ show a ++ " " ++ show fa ++ " )"
47
58
48
59
instance eqNonEmpty :: (Eq a , Eq (f a )) => Eq (NonEmpty f a ) where
49
60
eq (NonEmpty a1 fa1) (NonEmpty a2 fa2) = a1 == a2 && fa1 == fa2
50
61
51
62
instance ordNonEmpty :: (Ord a , Ord (f a )) => Ord (NonEmpty f a ) where
52
- compare (NonEmpty a1 fa1) (NonEmpty a2 fa2) =
63
+ compare (NonEmpty a1 fa1) (NonEmpty a2 fa2) =
53
64
case compare a1 a2 of
54
65
EQ -> compare fa1 fa2
55
66
other -> other
56
-
67
+
57
68
instance functorNonEmpty :: (Functor f ) => Functor (NonEmpty f ) where
58
69
map f (NonEmpty a fa) = NonEmpty (f a) (map f fa)
59
-
70
+
60
71
instance foldableNonEmpty :: (Foldable f ) => Foldable (NonEmpty f ) where
61
72
foldMap f (NonEmpty a fa) = f a <> foldMap f fa
62
73
foldl f b (NonEmpty a fa) = foldl f (f b a) fa
63
74
foldr f b (NonEmpty a fa) = f a (foldr f b fa)
64
-
75
+
65
76
instance traversableNonEmpty :: (Traversable f ) => Traversable (NonEmpty f ) where
66
77
sequence (NonEmpty a fa) = NonEmpty <$> a <*> sequence fa
67
78
traverse f (NonEmpty a fa) = NonEmpty <$> f a <*> traverse f fa
0 commit comments