Skip to content

Instantly share code, notes, and snippets.

@tmhedberg
Last active December 18, 2015 20:39
Show Gist options
  • Save tmhedberg/5841726 to your computer and use it in GitHub Desktop.
Save tmhedberg/5841726 to your computer and use it in GitHub Desktop.
Assertions with an optional descriptive message, with both monadic and non-monadic variants
{-# LANGUAGE DeriveDataTypeable, FlexibleInstances, OverlappingInstances #-}
module Assert where
import Control.Exception
import Data.Typeable
data AssertionFailure = AssertionFailure (Maybe String) deriving Typeable
instance Exception AssertionFailure
instance Show AssertionFailure where
show (AssertionFailure Nothing) = "Assertion failed"
show (AssertionFailure (Just msg)) = "Assertion failed: " ++ msg
class AssertResult ar where assert :: Bool -> ar
instance AssertResult (a -> a) where
assert True = id
assert False = throw $ AssertionFailure Nothing
instance AssertResult (String -> a -> a) where
assert True _ = id
assert False msg = throw $ AssertionFailure $ Just msg
instance Monad m => AssertResult (m a) where
assert True = return undefined
assert False = throw $ AssertionFailure Nothing
instance Monad m => AssertResult (String -> m a) where
assert True _ = return undefined
assert False msg = throw $ AssertionFailure $ Just msg
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment