gpt4 book ai didi

Haskell:使用镜头修改状态时 TChan 包装重复

转载 作者:行者123 更新时间:2023-12-02 04:35:28 25 4
gpt4 key购买 nike

考虑以下代码(和错误):

import Control.Lens
import Control.Monad.STM
import Control.Monad.IO.Class
import Control.Monad.State.Lazy
import Control.Concurrent.STM.TChan

data Broadcast = Broadcast Int

data ImmutableState = ImmutableState
{ _broadcastChan :: TChan Broadcast
, _encryption :: Int
}

makeLenses ''ImmutableState

helper :: MonadIO m => StateT ImmutableState m a
helper = do
broadcastChan <~ (liftIO . atomically $ dupTChan $ use broadcastChan)
{- ^
Test.hs:
Couldn't match expected type `Broadcast'
with actual type `TChan Broadcast'
Expected type: StateT ImmutableState m (TChan Broadcast)
Actual type: StateT ImmutableState m (TChan (TChan Broadcast))
In the second argument of `(<~)', namely
`(liftIO . atomically $ dupTChan $ use broadcastChan)'
In a stmt of a 'do' block:
broadcastChan
<~ (liftIO . atomically $ dupTChan $ use broadcastChan)
-}

forkImmState :: MonadIO m => ImmutableState -> m ImmutableState
forkImmState s = evalStateT helper s

有人可以解释一下(TChan (TChan Broadcast))是如何产生的吗?

最佳答案

dupTChan 需要一个像 TChan a 这样的参数,并且正在应用像 MonadState ImmutableState m => m (TChan Broadcast) 这样的东西。如果您直接尝试,您会得到稍微不同类型的错误

*Main> :t dupTChan $ use broadcastChan

<interactive>:1:12:
No instance for (MonadState ImmutableState TChan)
arising from a use of `use'
Possible fix:
add an instance declaration for (MonadState ImmutableState TChan)
In the second argument of `($)', namely `use broadcastChan'
In the expression: dupTChan $ use broadcastChan

GHC 尝试通过 a ~ TChan Broadcastm ~ TChan 来统一 TChan am(TChan Broadcast) ,但它失败了,因为 TChan 不是 MoandState 的实例。您已经可以看到 TChan(TChan Broadcast) 错误是如何形成的,但它无法统一,因此停止了。

只有当我们声称我们知道结果的类型时,GHC 才会告诉我们它在幕后尝试的内容

*Main> :t (dupTChan $ use broadcastChan) :: STM (TChan Broadcast)

<interactive>:1:2:
Couldn't match type `TChan Broadcast' with `Broadcast'
Expected type: STM (TChan Broadcast)
Actual type: STM (TChan (TChan Broadcast))
In the expression:
(dupTChan $ use broadcastChan) :: STM (TChan Broadcast)

关于Haskell:使用镜头修改状态时 TChan 包装重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17099881/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com