{-# LANGUAGE CPP #-}{-# LANGUAGE ConstraintKinds #-}{-# LANGUAGE KindSignatures #-}{-# LANGUAGE FlexibleContexts #-}{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 -}moduleMaybes(moduleData.Maybe,MaybeErr (..),-- Instance of MonadfailME ,isSuccess ,orElse ,firstJust ,firstJusts ,whenIsJust ,expectJust ,rightToMaybe ,-- * MaybeTMaybeT(..),liftMaybeT ,tryMaybeT )whereimportGhcPrelude importControl.MonadimportControl.Monad.Trans.MaybeimportControl.Exception(catch,SomeException(..))importData.MaybeimportUtil (HasCallStack)infixr4`orElse `{- ************************************************************************ * * \subsection[Maybe type]{The @Maybe@ type} * * ************************************************************************ -}firstJust::Maybea ->Maybea ->Maybea firstJust a b =firstJusts [a ,b ]-- | Takes a list of @Maybes@ and returns the first @Just@ if there is one, or-- @Nothing@ otherwise.firstJusts::[Maybea ]->Maybea firstJusts =msumexpectJust::HasCallStack=>String->Maybea ->a {-# INLINEexpectJust#-}expectJust _(Justx )=x expectJusterr Nothing=error("expectJust "++err )whenIsJust::Monadm =>Maybea ->(a ->m ())->m ()whenIsJust (Justx )f =f x whenIsJustNothing_=return()-- | Flipped version of @fromMaybe@, useful for chaining.orElse::Maybea ->a ->a orElse =flipfromMayberightToMaybe::Eithera b ->Maybeb rightToMaybe (Left_)=NothingrightToMaybe(Rightx )=Justx {- ************************************************************************ * * \subsection[MaybeT type]{The @MaybeT@ monad transformer} * * ************************************************************************ -}-- We had our own MaybeT in the past. Now we reuse transformer's MaybeTliftMaybeT::Monadm =>m a ->MaybeTm a liftMaybeT act =MaybeT$Just`liftM`act -- | Try performing an 'IO' action, failing on error.tryMaybeT::IOa ->MaybeTIOa tryMaybeT action =MaybeT$catch(Just`fmap`action )handler wherehandler (SomeException_)=returnNothing{- ************************************************************************ * * \subsection[MaybeErr type]{The @MaybeErr@ type} * * ************************************************************************ -}dataMaybeErr err val =Succeeded val |Failed err instanceFunctor(MaybeErr err )wherefmap =liftMinstanceApplicative(MaybeErr err )wherepure =Succeeded (<*> )=apinstanceMonad(MaybeErr err )whereSucceeded v >>= k =k v Failed e >>=_=Failed e isSuccess::MaybeErr err val ->BoolisSuccess (Succeeded {})=TrueisSuccess(Failed {})=FalsefailME::err ->MaybeErr err val failME e =Failed e