haskell 国家是一支箭吗?

bybem2ql  于 2023-10-19  发布在  其他
关注(0)|答案(1)|浏览(80)

每个人都知道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)

我已经确认CategoryArrowArrowChoiceArrowApply示例是正确的,但我不确定ArrowLoop示例。而且没有与箭头相关的类的QuickCheck。这些例子真的正确吗?

4si2a6ki

4si2a6ki1#

类别示例不正确。它不符合正确的身份法则:

f . id = f

但是,在.id的实现中,

(f . id) s      ==
(fst (f s) , s) /= 
f s

相关问题