每个人都知道State
是一个单子:
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
和ArrowApply
示例是正确的,但我不确定ArrowLoop
示例。而且没有与箭头相关的类的QuickCheck。这些例子真的正确吗?
1条答案
按热度按时间4si2a6ki1#
类别示例不正确。它不符合正确的身份法则:
但是,在
.
和id
的实现中,