Skip to content

Commit

Permalink
STT preserves Alternative (#33)
Browse files Browse the repository at this point in the history
Define Alternative instance for STT, add tests for unit laws.
  • Loading branch information
BebeSparkelSparkel authored Jan 4, 2024
1 parent 6412fcb commit b3afb10
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 0 deletions.
4 changes: 4 additions & 0 deletions Control/Monad/ST/Trans/Internal.hs
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,10 @@ instance (Monad m, Functor m) => Applicative (STT s m) where
(STTRet s3 x) <- n s2
return (STTRet s3 (f x))

instance (Monad m, Alternative m) => Alternative (STT s m) where
empty = STT $ \_ -> empty
STT m <|> STT n = STT $ \s# -> m s# <|> n s#

-- Instances of other monad classes

instance (MonadError e m, Functor m) => MonadError e (STT s m) where
Expand Down
5 changes: 5 additions & 0 deletions test/Main.hs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import Test.Tasty.HUnit

import GHC.STRef (STRef)
import GHC.Arr (Array, listArray, (//))
import Control.Applicative ((<|>), empty)
import Control.Monad.ST.Trans
import Control.Monad.IO.Class
import Control.Monad.Trans.Class
Expand All @@ -16,6 +17,10 @@ props = testGroup "Properties" [
\x -> runSTT (return x) == Just (x :: Int),
testProperty "STT respects MonadTrans" $
\m -> runSTT (lift m) == (m :: Maybe Int),
testProperty "STT respects Alternative Left" $
\m -> runSTT (lift m <|> empty) == (m :: Maybe Int),
testProperty "STT respects Alternative Right" $
\m -> runSTT (empty <|> lift m) == (m :: Maybe Int),
testProperty "newSTRef . readSTRef == id" $
\x -> runSTT ((newSTRef x :: STT s Maybe (STRef s Int)) >>= readSTRef) == Just x,
testProperty "writeSTRef overwrite" $
Expand Down

0 comments on commit b3afb10

Please sign in to comment.