大家都知道State
是一个 monad:
import Control.Monad
newtype State s a = State {runState :: s -> (a, s)}
instance Functor (State s) where
fmap = liftM
instance Applicative (State s) where
pure x = State (\s -> (x, s))
(<*>) = ap
instance Monad (State s) where
State f >>= k = State $ \s -> let
(x, s2) = f s
State g = k x
in g s2
但这也是箭头吗?这是我的实施尝试instance Arrow State
:
import Control.Arrow
import Control.Category
instance Category State where
id = State (\s -> (s, s))
State f . State g = State $ \x -> let
(y, x2) = g x
(z, _) = f y
in (z, x2)
instance Arrow State where
arr f = State (\s -> (f s, s))
State f *** State g = State $ \(s, t) -> let
(x1, s1) = f s
(y1, t1) = g t
in ((x1, y1), (s1, t1))
instance ArrowChoice State where
State f +++ State g = State $ \s -> case s of
Left s2 -> let
(x, s3) = f s2
in (Left x, Left s3)
Right s2 -> let
(y, s3) = g s2
in (Right y, Right s3)
instance ArrowApply State where
app = State (\k@(State f, s) -> (fst (f s), k))
instance ArrowLoop State where
loop (State f) = State $ \s -> let
((x, d), (s2, _)) = f (s, d)
in (x, s2)
我已经确认Category
、Arrow
和实例是正确的,但我不确定该实例ArrowChoice
。并且没有针对箭头相关类的 QuickCheck。这些例子真的正确吗?ArrowApply
ArrowLoop