4

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 e.g.

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 s a" part. If it where "State a s", 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.

4

1 回答 1

14

当您将数据类型定义为

data T a b = MkT { getA :: a, getB :: b }

读起来像

data T a b = MkT a b

自动定义了两个辅助函数:

getA :: (T a b) -> a
getA (MkT x _) = x

getB :: (T a b) -> b
getB (MkT _ y) = y

当您应用getA的值时T,结果为 类型a

现在您的State类型只包含一个元素,该类型是一个函数 ( :: s -> (a, s))。runState将类型的值转换State s a为该类型的函数。

ghci> :t runState
runState :: State s a -> s -> (a, s)

每次应用runState到 type 的值时State s a,结果都是 type 的函数s -> (a,s)。这个函数的第一个参数是状态变量(类型s)的初始值。

在教程示例中,

  • chncasewst3 'e' 'd' 'f'有类型State Bool String
  • 所以,runState (chncasewst3 'e' 'd' 'f')有类型Bool -> (String, Bool)
  • 所以,runState (chncasewst3 'e' 'd' 'f') False有类型(String, Bool)

进一步阅读:

于 2010-07-13T20:06:57.997 回答