I'm reading up on Monad tutorials, and the one I'm working on now is http://www.muitovar.com/monad/moncow.xhtml , but I ran on a problem with the state Monad, or to be more precise the runState accessor function.
The type is defined as
newtype State s a = State { runState :: (s -> (a,s)) }
and it's called eg
runState (chncasewst3 'e' 'd' 'f') False
I don't know how to read the definition for getting to the second line, especially because of the "State sa" part. If it where "State as", I could deduce that the accessor has been curried 'as far' as the 's'.
So the question is; how to read the type definition so that I could see how to call the accessor function in this situation, and if possible how to read accessor functions per se.
When you have a data type defined as
data T a b = MkT { getA :: a, getB :: b }
read it like
data T a b = MkT a b
with two helper functions defined automatically:
getA :: (T a b) -> a
getA (MkT x _) = x
getB :: (T a b) -> b
getB (MkT _ y) = y
When you apply getA
to the value of T
, the result is of type a
.
Now your State
type consists of only one element, which type is a function ( :: s -> (a, s)
). runState
converts a value of type State sa
to a function of this type.
ghci> :t runState
runState :: State s a -> s -> (a, s)
Every time you apply runState
to the value of type State sa
, the result is a function of type s -> (a,s)
. And the first argument of this function is an initial value of the state variable (of type s
).
In the tutorial example,
chncasewst3 'e' 'd' 'f'
has type State Bool String
. runState (chncasewst3 'e' 'd' 'f')
has type Bool -> (String, Bool)
. runState (chncasewst3 'e' 'd' 'f') False
has type (String, Bool)
. Further reading:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.