【问题标题】:What is wrong with this instance : ArrowApply Automaton?这个实例有什么问题:ArrowApply Automaton?
【发布时间】:2014-12-22 12:50:46
【问题描述】:

我希望 Automaton 有实例 ArrowApply,但 Control.Arrow.Transformer.Automaton 没有。 我认为以下代码会表现良好:

data Automaton b c = Auto {runAuto :: b -> (c, Automaton b c) }

app :: Automaton (Automaton b c, b) c
app = Auto $ \(f,x) -> let
    (u, m) = runAuto f x
    nextApp m = Auto $ \(_,x) -> let
        (u', n) = runAuto m x
      in (u', nextApp n)
  in (u, nextApp m)

可能,未使用的参数的存在是不好的。 但是我不能有任何坏例子的具体想法,请告诉我任何一个。

【问题讨论】:

标签: haskell


【解决方案1】:

不会满足ArrowApply laws

第一定律实际上失败了:

first (arr (\x -> arr (\y -> (x,y)))) >>> app = id
  :: ArrowApply a => a (t, d) (t, d)

我们先定义一个辅助函数:

iterateAuto :: [b] -> Auto b c -> [c]
iterateAuto [] _ = []
iterateAuto (x:xs) a = let (y, a') = runAuto a x
                     in y : iterateAuto xs a'

在右边我们得到:

*Main> iterateAuto [(0,0), (1,0)] (id :: Auto (Int, Int) (Int, Int))
[(0,0),(1,0)]

但是在左侧(这里我必须将您的实现命名为app'

iterateAuto [(0,0), (1,0)] (first (arr (\x -> arr (\y -> (x,y)))) >>> app' :: Auto (Int, Int) (Int, Int))
[(0,0),(0,0)]

我很确定,如果ArrowApply 可能用于Automaton,它会在arrows 包中。很难解释为什么不能有一个。我试图解释我的直觉。 ArrowApply 等价于Monad,而app 是一种一元的joinAutomaton 是一种有状态的计算,但每个 Automaton 都有自己的状态,而不是 State monad 中的全局状态。在纯设置中,自动机的下一个状态会在结果对中的每次迭代中提供给我们。然而,如果我们有app,内部自动机的状态就会丢失。

app 的另一个幼稚实现:

app'' :: Auto (Auto b c, b) c
app'' = Automaton $ \(f,x) -> let
    (u, m) = runAuto f x
    nextApp = app''
  in (u, nextApp)

第二定律会失败

first (arr (g >>>)) >>> app = second g >>> app

让我们把有状态的incr 当作g

incr :: Auto Int Int
incr = incr' 0
  where incr' n = Automaton $ \x -> (x + n, incr' $ n + 1)

和辅助方法

helper :: Arrow a => (Int, Int) -> (a Int Int, Int)
helper (x, y) = (arr (+x), y)

然后我们看到这个等式也不适用于非常简单的输入:

*Main> iterateAuto (map helper [(0,0),(0,0)]) $ first (arr (incr >>>)) >>> app''
[0,0]
*Main> iterateAuto (map helper [(0,0),(0,0)]) $ second incr >>> app''
[0,1]

我有the runnable code as a gist

一个邪恶的想法是通过利用 IORef 或 STRef 来制作 Automaton 的一个版本

data STAutomaton s a b c = STAutomaton (STRef s (Automaton a b c))

但这可能是使用Kleisli (ST s)Kleisli IO 的尴尬方式。

【讨论】:

  • 谢谢!事实上,我想做一个与STAutomaton 相同的Arrow。可以将其设为ArrowApply 的正确实例吗?还是实施“地方国家”的错误方式? (现在我在想ArrowCircuit 可以代表变量,所以我正在尝试。你怎么看?)
  • 最近的 ICFP 论文中提出了一些不错的技巧。我没有做这个练习,但你应该能够使用来自ArrowCircuitArrowChoicedelay模拟本地状态:youtube.com/watch?v=zgNRM8tZguY
猜你喜欢
  • 2018-09-05
  • 2021-10-17
  • 2011-09-28
  • 2011-12-14
  • 2017-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多