Skip to content

Commit bb63d2e

Browse files
authored
add run1 run2 solution (#44)
1 parent 3d7151f commit bb63d2e

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

MonadTransformers/4.5/stateList.hs

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
{-# LANGUAGE FlexibleContexts #-}
2+
module StateList where
3+
4+
import Control.Monad.Except
5+
import Control.Monad.State
6+
import Data.Foldable
7+
8+
9+
limited :: (MonadError Int m, MonadState s m) => (s -> Bool) -> [State s a] -> m [a]
10+
limited p fs = traverse limit1 (zip [0..] fs) where
11+
limit1 (i, f) = do
12+
a <- state (runState f)
13+
stateIsBad <- gets (not . p)
14+
when stateIsBad $ throwError i
15+
return a
16+
17+
18+
runLimited1 :: (s -> Bool) -> [State s a] -> s -> (Either Int [a], s)
19+
runLimited1 p fs s = run1 (limited p fs) s
20+
21+
22+
runLimited2 :: (s -> Bool) -> [State s a] -> s -> Either Int ([a], s)
23+
runLimited2 p fs s = run2 (limited p fs) s
24+
25+
26+
run1 :: ExceptT Int (State s) [a] -> s -> (Either Int [a], s)
27+
run1 m s = runState (runExceptT m) s
28+
29+
30+
run2 :: StateT s (Except Int) [a] -> s -> Either Int ([a], s)
31+
run2 m s = runExcept $ runStateT m s

0 commit comments

Comments
 (0)