haskellstatearrows

Is State an arrow?


Everyone knows State is a 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

But is it an arrow as well? Here's my attempt of implementing 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)

I've confirmed that the Category, Arrow, ArrowChoice and ArrowApply instances are correct, but I'm unsure about the ArrowLoop instance. And there is no QuickCheck for arrow-related classes. Are these instances really correct?


Solution

  • The category instance is not correct. It fails the right identity law:

    f . id = f
    

    But, in your implementation of . and id,

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