Skip to content

Instantly share code, notes, and snippets.

@qzchenwl
Created August 29, 2011 17:36
Show Gist options
  • Save qzchenwl/1178905 to your computer and use it in GitHub Desktop.
Save qzchenwl/1178905 to your computer and use it in GitHub Desktop.
-- file: ch15/Supply.hs
next = S $ do st <- get
case st of
[] -> return Nothing
(x:xs) -> do put xs
return (Just x)
@qzchenwl
Copy link
Author

Why st is type of [a] but not Maybe a ?

@md2perpe
Copy link

The "method" get returns the state used in the state monad. That will be [a] because you match st against [] and (x:xs). The full do expression will however be State [a](Maybe a) since you return Just x which is of type Maybe a.

@qzchenwl
Copy link
Author

@md2perpe This is an example from Real World Haskell.
The get is defined as:

get :: State s s
get = State $ \s -> (s, s)

The (>>=) is defined as:

bindState :: State s a -> (a -> State s b) -> State s b
bindState m k = State $ \s -> let (a, s') = runState m s
                              in runState (k a) s'

We can apply function (\s -> let (a, s') = runState m s ...) on st, so st must have type of s for State s a
In the Supply example, State [a] (Maybe a) ... I think I know...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment