module Data.Strict.Maybe (
    Maybe(..)
  , isJust
  , isNothing
  , fromMaybe
  , maybe
  , listToMaybe
  , maybeToList
  , mapMaybe
  , catMaybes
) where
import qualified Data.Maybe as L
import Prelude hiding (Maybe(..), maybe)
import Data.Semigroup (Semigroup(..))
import GHC.Generics (Generic, Generic1)
import Data.Data (Data, Typeable)
import Data.Strict.Class
data Maybe a = Nothing | Just !a
  deriving (Eq, Ord, Show, Read, Functor, Foldable, Traversable, Generic, Generic1, Data, Typeable)
instance IsStrict (L.Maybe a) (Maybe a) where
  toStrict   L.Nothing  = Nothing
  toStrict   (L.Just x) = Just x
  fromStrict Nothing    = L.Nothing
  fromStrict (Just x)   = L.Just x
instance Semigroup a => Semigroup (Maybe a) where
  Nothing <> m       = m
  m       <> Nothing = m
  Just x1 <> Just x2 = Just (x1 <> x2)
instance Monoid a => Monoid (Maybe a) where
  mempty                    = Nothing
  Nothing `mappend` m       = m
  m       `mappend` Nothing = m
  Just x1 `mappend` Just x2 = Just (x1 `mappend` x2)
isJust :: Maybe a -> Bool
isJust Nothing = False
isJust _       = True
isNothing :: Maybe a -> Bool
isNothing Nothing = True
isNothing _       = False
fromMaybe :: a -> Maybe a -> a
fromMaybe x Nothing  = x
fromMaybe _ (Just y) = y
maybe :: b -> (a -> b) -> Maybe a -> b
maybe x _ Nothing  = x
maybe _ f (Just y) = f y
listToMaybe :: [a] -> Maybe a
listToMaybe []    = Nothing
listToMaybe (a:_) = Just a
maybeToList :: Maybe a -> [a]
maybeToList Nothing  = []
maybeToList (Just x) = [x]
catMaybes :: [Maybe a] -> [a]
catMaybes ls = [x | Just x <- ls]
mapMaybe :: (a -> Maybe b) -> [a] -> [b]
mapMaybe _ []     = []
mapMaybe f (x:xs) =
  case f x of
    Nothing -> rs
    Just r  -> r:rs
  where rs = mapMaybe f xs