패턴 일치/가드를 사용하여 a
함수를 쓸 수 있습니까? 주 (state) 모나드 (monad) 필드에서 일치를 패닝하는 방법은 무엇입니까?
{-# 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' :: State MyState String
a' | i <- gets counter, i == 0 = return "hello"
로 a
를 작성 시도했지만 오류 가지고 :
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"
LambdaCase가 매우 좋습니다. –
나는 람다 케이스를 골랐다. 덕분에 –
모든 브랜치가'return'으로 시작했기 때문에'(<&>) = flip fmap'을 다음과 같이 다시 쓸 수있다 :'gets counter <&> \ case 0 -> "hello"; 1 -> "bye". '(<&>)는 렌즈 패키지에 있습니다 https://hackage.haskell.org/package/lens-4.13.2.1/docs/Control-Lens-Operators.html#v:--------62- –