Last active
May 17, 2017 16:56
-
-
Save kl0tl/57ebdac9f20f77e03e711dbe857eb583 to your computer and use it in GitHub Desktop.
`Semigroup`(s), `Monoid`(s) and `Alt`(s) instances
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# LANGUAGE NoImplicitPrelude, GeneralizedNewtypeDeriving #-} | |
class Semigroup a where | |
(<>) :: a -> a -> a | |
class (Semigroup a) => Monoid a where | |
mempty :: a | |
class Functor f where | |
fmap :: (a -> b) -> f a -> f b | |
class (Functor f) => Alt f where | |
(<|>) :: f a -> f a -> f a | |
class (Alt f) => Plus f where | |
zero :: f a | |
data Maybe a = Nothing | Just a | |
instance (Semigroup a) => Semigroup (Maybe a) where | |
Nothing <> r = r | |
l <> Nothing = l | |
(Just l) <> (Just r) = Just (l <> r) | |
instance (Semigroup a) => Monoid (Maybe a) where | |
mempty = Nothing | |
-- instance (Semigroup a) => Semigroup (Maybe a) where | |
-- Nothing <> _ = Nothing | |
-- _ <> Nothing = Nothing | |
-- (Just l) <> (Just r) = Just (l <> r) | |
-- instance (Monoid a) => Monoid (Maybe a) where | |
-- mempty = Just mempty | |
instance Functor Maybe where | |
fmap _ Nothing = Nothing | |
fmap f (Just x) = Just (f x) | |
newtype First a = First (Maybe a) | |
deriving Functor | |
instance Alt First where | |
(First Nothing) <|> r = r | |
l <|> _ = l | |
instance Plus First where | |
zero = First Nothing | |
-- instance Alt First where | |
-- _ <|> r@(First Nothing) = r | |
-- l <|> _ = l | |
newtype Last a = Last (Maybe a) | |
deriving Functor | |
instance Alt Last where | |
l <|> (Last Nothing) = l | |
_ <|> r = r | |
instance Plus Last where | |
zero = Last Nothing | |
-- instance Alt Last where | |
-- l@(Last Nothing) <|> _ = l | |
-- _ <|> r = r |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment