Haskell中State的Functor/Applicative实例

dan*_*tin 11 monads haskell functor applicative

在阅读(并略读)Wadler关于monad的论文之后,我决定更仔细地研究这篇论文,为他描述的每个monad定义函子和应用实例.使用类型同义词

type M a = State -> (a, State)
type State = Int
Run Code Online (Sandbox Code Playgroud)

Wadler用于定义状态monad,我有以下(使用相关的名称,所以我可以稍后用newtype声明定义它们).

fmap' :: (a -> b) -> M a -> M b
fmap' f m = \st -> let (a, s) = m st in (f a, s)

pure' :: a -> M a
pure' a = \st -> (a, st)

(<@>) :: M (a -> b) -> M a -> M b
sf <@> sv = \st -> let (f, st1) = sf st
                       (a, st2) = sv st1
                    in (f a, st2)

return' :: a -> M a
return' a = pure' a

bind :: M a -> (a -> M b) -> M b
m `bind` f = \st -> let (a, st1) = m st
                        (b, st2) = f a st1
                     in (b, st2)
Run Code Online (Sandbox Code Playgroud)

当我在newtype声明中切换到使用类型构造函数时,例如,

newtype S a = S (State -> (a, State))
Run Code Online (Sandbox Code Playgroud)

一切都崩溃了.例如,一切都只是稍作修改

instance Functor S where
 fmap f (S m) = S (\st -> let (a, s) = m st in (f a, s)) 

instance Applicative S where
 pure a = S (\st -> (a, st))
Run Code Online (Sandbox Code Playgroud)

但是,由于lambda表达式隐藏在该类型构造函数中,因此GHC中没有任何内容运行.现在我看到的唯一解决方案是定义一个函数:

isntThisAnnoying s (S m) = m s
Run Code Online (Sandbox Code Playgroud)

为了将s绑定到'st'并实际返回一个值,例如,

fmap f m = S (\st -> let (a, s) = isntThisAnnoying st m in (f a, s))
Run Code Online (Sandbox Code Playgroud)

还有另一种不使用这些辅助功能的方法吗?

Dan*_*att 11

如果你看这里,你会看到他们这样定义:

newtype State s a = State { runState :: (s -> (a,s)) }
Run Code Online (Sandbox Code Playgroud)

以便给内在的lambda一个名字.

  • 这也意味着`runState = flip isntThisAnnoying`. (3认同)

Dan*_*kov 5

通常的方法是定义newtype newtype S a = S {runState : State -> (a, State)}。然后,而不是你的isntThisAnnoying s (S m),你可以写runState t s在那里t是一样的S m
您必须使用a,newtype因为类型同义词不能是类型类实例。