(original) (raw)

{-# LANGUAGE Trustworthy #-} {-# LANGUAGE NoImplicitPrelude #-}

module Data.Maybe ( Maybe(Nothing,Just)

, maybe

, isJust , isNothing , fromJust , fromMaybe , listToMaybe , maybeToList , catMaybes , mapMaybe ) where

import GHC.Base

maybe :: b -> (a -> b) -> Maybe a -> b maybe n _ Nothing = n maybe _ f (Just x) = f x

isJust :: Maybe a -> Bool isJust Nothing = False isJust _ = True

isNothing :: Maybe a -> Bool isNothing Nothing = True isNothing _ = False

fromJust :: Maybe a -> a fromJust Nothing = errorWithoutStackTrace "Maybe.fromJust: Nothing" fromJust (Just x) = x

fromMaybe :: a -> Maybe a -> a fromMaybe d x = case x of {Nothing -> d;Just v -> v}

maybeToList :: Maybe a -> [a] maybeToList Nothing = [] maybeToList (Just x) = [x]

listToMaybe :: [a] -> Maybe a listToMaybe = foldr (const . Just) Nothing {-# INLINE listToMaybe #-}

catMaybes :: [Maybe a] -> [a] catMaybes ls = [x | Just x <- ls]

mapMaybe :: (a -> Maybe b) -> [a] -> [b] mapMaybe _ [] = [] mapMaybe f (x:xs) = let rs = mapMaybe f xs in case f x of Nothing -> rs Just r -> r:rs {-# NOINLINE [1] mapMaybe #-}

{-# RULES "mapMaybe" [~1] forall f xs. mapMaybe f xs = build (\c n -> foldr (mapMaybeFB c f) n xs) "mapMaybeList" [1] forall f. foldr (mapMaybeFB (:) f) [] = mapMaybe f #-}

{-# INLINE [0] mapMaybeFB #-} mapMaybeFB :: (b -> r -> r) -> (a -> Maybe b) -> a -> r -> r mapMaybeFB cons f x next = case f x of Nothing -> next Just r -> cons r next