简体   繁体   English

Functor实例的状态

[英]Functor instance of State

instance Functor (State s) where
  fmap f (State g) = State $ \s0 -> 
      let (a, s1) = g s0
      in (f a, s1)

It is implementation of Functor for State . 它是StateFunctor实现。 I cannot understand how does it work? 我无法理解它是如何工作的? Especially, g is used as it would be a function but on my eye it is not a function. 特别是, g被用作它的功能,但在我看来它不是一个功能。 It is just object ( perhaps function) but I cannot understand why it is function. 它只是对象(也许是函数),但我无法理解为什么它是函数。 After all, it should be some state so it can for example Int 毕竟,它应该是一些状态,所以它可以例如Int

Please make clear. 请说清楚。

It looks like your state type looks like: 看起来您的州类型如下:

data State s a = State (s -> (a ,s))

so your fmap function should have type: 所以你的fmap函数应该有类型:

fmap :: (a -> b) -> (State s a) -> (State s b)

when you match on the input state value in 当您匹配输入状态值时

fmap f (State g) = State $ \s0 -> 

g is a function s -> (a, s) and you need to construct one of type s -> (b, s) . g是一个函数s -> (a, s) ,你需要构造一个类型s -> (b, s)

(a, s1) = g s0

applies the input state to the existing stateful computation, binding a to the result and s1 to the new state. 将输入状态应用于现有的有状态计算,将a绑定到结果,将s1绑定到新状态。 It then applies f to a to obtain the mapped result value in 然后将f应用于a以获取映射结果值

(f a, s1)

while the state returned from g is unchanged. 而从g返回的州没有变化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM