on master help sign in
Replace the Monoid instance on Maybe
220011eDavid Raymond Christiansen
CHANGELOG+3
@@ -21,6 +21,9 @@ New in 0.9.18:
21 requiring a separate lemma.
21 requiring a separate lemma.
22* Case alternatives are allowed to be impossible:
22* Case alternatives are allowed to be impossible:
23 case Vect.Nil {a=Nat} of { (x::xs) impossible ; [] => True }
23 case Vect.Nil {a=Nat} of { (x::xs) impossible ; [] => True }
24+* The default Semigroup and Monoid instances for Maybe are now prioritised
25+ choice, keeping the first success as Alternative does. The version that
26+ collects successes is now a named instance.
24
27
25New in 0.9.17:
28New in 0.9.17:
26--------------
29--------------
libs/prelude/Prelude/Maybe.idr+18−10
@@ -78,17 +78,25 @@ instance (Eq a) => Eq (Maybe a) where
78 (Just _) == Nothing = False
78 (Just _) == Nothing = False
79 (Just a) == (Just b) = a == b
79 (Just a) == (Just b) = a == b
80
80
81−-- Lift a semigroup into 'Maybe' forming a 'Monoid' according to
81+||| Prioritised choice. Just like the `Alternative` instance, the
82−-- <http://en.wikipedia.org/wiki/Monoid>: "Any semigroup S may be
82+||| `Semigroup` for `Maybe a` keeps the first succeeding computation.
83−-- turned into a monoid simply by adjoining an element i not in S
83+|||
84−-- and defining i+i = i and i+s = s = s+i for all s in S."
84+||| **NB**: This is a different choice than in the Haskell libraries.
85−
85+||| Use `collectJust` to get the Haskell behaviour.
86+instance Semigroup (Maybe a) where
87+ Nothing <+> m = m
88+ (Just x) <+> _ = Just x
89+
90+||| Transform any semigroup into a monoid by using `Nothing` as the
91+||| designated neutral element and collecting the contents of the
92+||| `Just` constructors using a semigroup structure on `a`. This is
93+||| the behaviour in the Haskell libraries.
86−instance (Semigroup a) => Semigroup (Maybe a) where
94+instance [collectJust] Semigroup a => Semigroup (Maybe a) where
87− Nothing <+> m = m
95+ Nothing <+> m = m
88− m <+> Nothing = m
96+ m <+> Nothing = m
89 (Just m1) <+> (Just m2) = Just (m1 <+> m2)
97 (Just m1) <+> (Just m2) = Just (m1 <+> m2)
90
98
91−instance (Semigroup a) => Monoid (Maybe a) where
99+instance Monoid (Maybe a) where
92 neutral = Nothing
100 neutral = Nothing
93
101
94instance (Monoid a, Eq a) => Cast a (Maybe a) where
102instance (Monoid a, Eq a) => Cast a (Maybe a) where
@@ -98,5 +106,5 @@ instance (Monoid a) => Cast (Maybe a) a where
98 cast = lowerMaybe
106 cast = lowerMaybe
99
107
100instance Foldable Maybe where
108instance Foldable Maybe where
101− foldr _ z Nothing = z
109+ foldr _ z Nothing = z
102 foldr f z (Just x) = f x z
110 foldr f z (Just x) = f x z