Instantly share code, notes, and snippets.

Embed
What would you like to do?
import Control.Monad (foldM)
data MyState s a = MyState { run :: s -> (a, s) }
instance Functor (MyState s) where
fmap f (MyState g) = MyState (\s -> let (a, s') = g s
in (f a, s'))
instance Applicative (MyState s) where
pure a = MyState (\s -> (a, s))
(MyState f) <*> (MyState g) = MyState (\s ->
let (f', s') = f s
(a, s'') = g s'
in (f' a, s''))
instance Monad (MyState s) where
return = pure
(MyState g) >>= f = MyState (\s ->
let (a, s') = g s
ns = f a
in run ns s')
getState :: MyState s s
getState = MyState (\s -> (s,s))
setState :: s -> MyState s ()
setState new = MyState (\s -> ((), new))
zipIndex :: [a] -> ([(Int, a)], Int)
zipIndex xs = run (innerZipIndex xs) 0
where
innerZipIndex :: [a] -> MyState Int [(Int, a)]
innerZipIndex xs = foldM step [] xs
step :: [(Int, a)] -> a -> MyState Int [(Int, a)]
step acc e = do
i <- getState
setState (i + 1)
return $ (i, e) : acc
main :: IO ()
main = do
let x = [10,20,30,40,50]
y = take 1000000 (repeat 1)
result = zipIndex x
putStrLn (show . reverse . fst $ result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment