是否有可能实现`(Applicative m)=>应用(StateT s m)`? [英] Is it possible to implement `(Applicative m) => Applicative (StateT s m)`?

查看:92
本文介绍了是否有可能实现`(Applicative m)=>应用(StateT s m)`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在研究 Data.Fresh Control.Monad.Trans.Fresh ,其中,定义一个生成新变量的接口,以及一个实现这个接口的monad变换器。

我最初认为可以实现 Applicative 实例为我的 FreshT vm ,唯一要求 Applicative m 存在。但是,我被卡住了,好像我需要 Monad m 。不信任我的Haskell-fu,然后转向变形金刚包,并且对我在 Control.Monad.Trans.State.Lazy 和<$ c $中找到的内容感到惊讶c> .Strict :

  instance(Functor m,Monad m)=>应用(StateT sm)其中
pure =返回
(*)= ap

所以,这里是我的问题:是否有可能用下面的实例头创建一个具有等价语义的实例?

 实例(应用m)=> Applicative(StateT sm)where 


解决方案

考虑到你有两个功能:

  f :: s  - > m(s,a  - > b)
g :: s - > m(s,a)

您要创建一个函数 h = StateT f * StateF g

  h :: s  - > m(s,b)

从上面可以看出 s 你可以传递给 f ,所以你有:

  f':: m(s,a  - > b)
g :: s - > m(s,a)

然而,要获得 s out of f'你需要Monad(无论你使用application,它仍然是 ms g )。



你可以使用定义并使用免费monad ,但对于状态崩溃,您需要加入


I'm currently working on Data.Fresh and Control.Monad.Trans.Fresh, which resp. define an interface for generating fresh variables, and a monad transformer which implements this interface.

I initially thought it would be possible to implement the Applicative instance for my FreshT v m with the only requirement that Applicative m exists. However, I got stuck and it seemed like I need to require Monad m. Not trusting my Haskell-fu, I then turned to the transformers package, and was surprised by what I found in Control.Monad.Trans.State.Lazy and .Strict:

instance (Functor m, Monad m) => Applicative (StateT s m) where
    pure = return
    (<*>) = ap

So here is my question: is it possible to create an instance with equivalent semantics with the following instance head?

instance (Applicative m) => Applicative (StateT s m) where

解决方案

Consider that you have two functions:

 f :: s -> m (s, a -> b)
 g :: s -> m (s, a)

And you want to create a function h = StateT f <*> StateF g

 h :: s -> m (s, b)

From the above you have an s you can pass to f so you have:

 f' :: m (s, a -> b)
 g :: s -> m (s, a)

However to get s out of f' you need the Monad (whatever you'd do with applicative it would still be in form of m s so you would not be able to apply the value to g).

You can play with the definitions and use free monad but for the collapse of state you need join.

这篇关于是否有可能实现`(Applicative m)=&gt;应用(StateT s m)`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆