4

我重新发明了某种“状态箭头”:

import Prelude hiding (id, (.))
import Control.Monad.State
import Control.Arrow
import Control.Category

data StateA s a b = StateA {runStateA :: s -> a -> (b, s)}

instance Category (StateA s) where
  id = StateA (\s a -> (a, s))

  (StateA f) . (StateA g) = StateA $ \s x -> let (b, s') = g s x in f s' b

instance Arrow (StateA s) where
  arr f = StateA $ \s a -> (f a, s)

  first (StateA f) = StateA $ \s (b, d) -> let (c, s') = f s b in ((c, d), s)

put' :: s -> StateA s b ()
put' s = StateA $ \_ _ -> ((), s)

get' :: StateA s b s
get' = StateA $ \s _ -> (s, s)

merge :: (s -> s -> s) -> StateA s a b -> StateA s a c -> StateA s a (b, c)
merge f (StateA a) (StateA b) = StateA $ \s x ->
  let (ra, sa) = a s x
      (rb, sb) = b s x 
  in ((ra, rb), f sa sb)


 test = (flip runStateA) s bar 
   where bar = ((put' 7) >>> get') &&& get'

似乎这个定义如我所愿:至少测试 3 5产量

((7,3), 3)

请注意,这种行为故意不同于像这样包裹在箭头中的普通 State monad:

liftKC = Kleisli . const

putM :: a -> Kleisli (State a) b ()
putM = liftKC . put

getM :: Kleisli (State a) b a
getM = liftKC get

foo :: (Num a) => Kleisli (State a) a (a, a)
foo = (putM 7 >>> getM) &&& getM

testKleisli a b = (flip runState) a $
                  (flip runKleisli) b foo

作为testKleisli 3 5返回

((7, 7), 7).

关键是人们可以分别操纵某些“并行计算分支”中的状态,然后以某种方式合并它。

我不熟悉箭头符号,但在这里很不方便:看起来它为每次计算都创建了新的“分支”。是否可以使用箭头符号重写“bar”函数(来自测试的 where 子句)?

4

1 回答 1

11

让我们画一张图

bar = ((put' 7) >>> get') &&& get'

让我们了解如何用箭头符号编写它。

put' 7 and get' 沿着最上面一行走,然后 get' 沿着底部走

就像一元do符号一样,proc符号引入了命名变量,取代了组合符,例如>>=显式传递值。

无论如何,我们可以看到我们需要将输入 , 馈送x到两侧,给出:

bar' = proc x -> do
        wasput <- put' 7 >>> get' -< x
        justgot <- get' -< x
        returnA -< (wasput,justgot)

或者如果我们希望一切都从右到左,等价地

bar'' = proc x -> do
        wasput <- get' <<< put' 7 -< x
        justgot <- get' -< x
        returnA -< (wasput,justgot)

测试

我将重构test多个测试:

test s b = (flip runStateA) s b

所以我们得到

ghci> test bar 3 5
((7,3),3)
ghci> test bar' 3 5
((7,3),3)
ghci> test bar'' 3 5
((7,3),3)

我们可以不写>>>吗?

我们可能会想排除(>>>)

bar''' = proc x -> do
        put7 <- put' 7 -< x
        wasput <- get' -< put7
        justgot <- get' -< x
        returnA -< (wasput,justgot)

哎呀,不:

ghci> test bar''' 3 5
((3,3),3)

正如您所指出的,您的状态是本地化的,并且put' 7不会通过任何一个线程get',所以我们还没有设法摆脱>>>or<<<组合子。

我不禁觉得这违反了某些箭头法则或其他法则。嗯……

断箭法

我花了一段时间才找到,但经过大量的脱糖和对图表皱眉之后,我发现一个箭头法则盯着我的脸,你的实例坏了:

first (f >>> g) = first f >>> first g

如果我们定义

dup :: Arrow a => a t (t, t)
dup = arr (\x -> (x,x))    

我们得到

ghci> test (dup >>> (first (put' 7    >>>     get'))) 1 3
((7,3),1)
ghci> test (dup >>> (first (put' 7) >>> first get')) 1 3
((1,3),1)

这是因为put' 7第二个示例中的本地化状态不会进入第二个first,如果您可以遵循所有这些第一个和第二个!

结论:

您发现箭头符号对您的箭头实例不太有用,因为它假定通过不成立的定律进行转换是可以的。

可悲的是,惠斯特确实非常有趣,而且非常有趣,它不是真正的箭。

于 2014-02-18T22:01:21.127 回答