gpt4 book ai didi

haskell - 如何在状态 monad 的字段上进行模式匹配?

转载 作者:行者123 更新时间:2023-12-01 16:13:37 25 4
gpt4 key购买 nike

是否可以使用模式匹配/守卫编写函数a

{-# LANGUAGE PatternGuards #-}
import Control.Monad.State.Strict(State, gets, runStateT)
data MyState = MyState
{ counter :: Int
} deriving (Show)


a :: State MyState String
a = do
i <- gets counter
case i of
0 -> return "hello"
1 -> return "bye"

run = runStateT a ( MyState{counter=0} )

我尝试将 a 写成

a' :: State MyState String
a' | i <- gets counter, i == 0 = return "hello"

但出现错误:

No instance for (Control.Monad.State.Class.MonadState MyState m0)
arising from a use of ‘gets’
The type variable ‘m0’ is ambiguous
Note: there are several potential instances:
instance Control.Monad.State.Class.MonadState s m =>
Control.Monad.State.Class.MonadState
s (Control.Monad.Trans.Cont.ContT r m)
-- Defined in ‘Control.Monad.State.Class’
instance (Control.Monad.Trans.Error.Error e,
Control.Monad.State.Class.MonadState s m) =>
Control.Monad.State.Class.MonadState
s (Control.Monad.Trans.Error.ErrorT e m)
-- Defined in ‘Control.Monad.State.Class’
instance Control.Monad.State.Class.MonadState s m =>
Control.Monad.State.Class.MonadState
s (Control.Monad.Trans.Except.ExceptT e m)
-- Defined in ‘Control.Monad.State.Class’
...plus 12 others
In a stmt of a pattern guard for
an equation for ‘a'’:
i <- gets counter
In an equation for ‘a'’:
a' | i <- gets counter, i == 0 = return "hello"

No instance for (Eq (m0 Int)) arising from a use of ‘==’
The type variable ‘m0’ is ambiguous
Relevant bindings include
i :: m0 Int (bound at src/TestGen/Arbitrary/Helpers/Z.hs:18:6)
Note: there are several potential instances:
instance Eq a => Eq (GHC.Real.Ratio a) -- Defined in ‘GHC.Real’
instance (Eq e, Data.Functor.Classes.Eq1 m, Eq a) =>
Eq (Control.Monad.Trans.Error.ErrorT e m a)
-- Defined in ‘Control.Monad.Trans.Error’
...plus 118 others
In the expression: i == 0
In a stmt of a pattern guard for
an equation for ‘a'’:
i == 0
In an equation for ‘a'’:
a' | i <- gets counter, i == 0 = return "hello"

最佳答案

这是不可能的。模式保护语法中的左箭头大部分与do-notation中的左箭头无关。

如果您愿意,可以使用新的 lambda-case 扩展:

{-# LANGUAGE LambdaCase #-}
a :: State MyState String
a = gets counter >>= \case
0 -> return "hello"
1 -> return "bye"

或者多路,如果,也许?

{-# LANGUAGE MultiWayIf #-}
a :: State MyState String
a = do
i <- gets counter
if
| i == 0 -> return "hello"
| i == 1 -> return "bye"

关于haskell - 如何在状态 monad 的字段上进行模式匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26612403/

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