Mok*_*sha 5 haskell arrows frp netwire
在这篇文章中出色的答案的引导下,我试图获得一个ArrowLoop不使用箭头表示法的工作示例。在我完全理解箭头在幕后的工作原理之前,我对使用箭头表示法感到不舒服。话虽这么说,我已经构建了一个小程序,基于我对 Arrows 的(有限)理解应该可以工作。然而,它最终以可怕的异常终止<<loop>>:
module Main where
import Control.Wire
import FRP.Netwire
farr :: SimpleWire (Int, Float) (String, Float)
farr = let
fn :: Int -> Float -> ((String, Float), SimpleWire (Int, Float) (String, Float))
fn i f = (("f+i: " ++ (show (fromIntegral i + f)), f + 0.1), loopFn)
loopFn :: SimpleWire (Int, Float) (String, Float)
loopFn = mkSFN $ \(i, f) -> fn i f
in
mkSFN $ \(i, _) -> fn i 0.0
main :: IO ()
main = do
let sess = clockSession_ :: Session IO (Timed NominalDiffTime ())
(ts, sess2) <- stepSession sess
let wire = loop farr
(Right s, wire2) = runIdentity $ stepWire wire ts (Right 0)
putStrLn ("s: " ++ s)
(ts2, _) <- stepSession sess2
let (Right s2, _) = runIdentity $ stepWire wire2 ts (Right 1)
putStrLn ("s2: " ++ s2)
Run Code Online (Sandbox Code Playgroud)
我的直觉告诉我,<<loop>>当您不向循环提供初始值时,通常会出现异常。我不是用包含 的行做到了这一点吗fn i 0.0?输出不一致:
$ ./test
s: f+i: 0.0
test.exe: <<loop>>
Run Code Online (Sandbox Code Playgroud)
有谁知道我做错了什么?
混乱的主要点似乎是ArrowLoop和之间的整体关系mfix。对于外行来说,是一个找到给定函数不动点fix的函数:
fix :: (a -> a) -> a
fix f = let x = f x in x
Run Code Online (Sandbox Code Playgroud)
mfix是这个函数的单子扩展,不出所料,其类型签名是:
mfix :: (a -> m a) -> m a
Run Code Online (Sandbox Code Playgroud)
那么这有什么关系呢ArrowLoop?好吧, Netwire 的实例在传递的线路的第二个参数上ArrowLoop运行。mfix换句话说,请考虑以下类型签名loop:
loop :: a (b, d) (c, d) -> a b c
Run Code Online (Sandbox Code Playgroud)
在 Netwire 中, 的实例ArrowLoop是:
instance MonadFix m => ArrowLoop (Wire s e m)
Run Code Online (Sandbox Code Playgroud)
这意味着该loop函数与连线一起使用时的类型为:
loop :: MonadFix m => Wire s e m (b, d) (c, d) -> Wire s e m b c
Run Code Online (Sandbox Code Playgroud)
由于loop不采用类型的初始参数d,这意味着无法通过线路初始化任何类型的常规“循环”。从中获取值的唯一方法是继续将输出用作输入,直到找到终止条件,这类似于fix工作方式。作为参数传递给 的连线loop实际上不会执行多次,因为stepWire它会使用不同的输入一遍又一遍地应用于同一条连线。仅当连线实际产生固定值时,函数才会步进并产生另一条连线(其行为与第一条连线相同)。
为了完整起见,这里是我对应该如何loop工作的最初直觉的代码,我将其命名为semiLoop:
semiLoop :: (Monad m, Monoid s, Monoid e) => c -> Wire s e m (a, c) (b, c) -> Wire s e m a b
semiLoop initialValue loopWire = let
runLoop :: (Monad m, Monoid s, Monoid e) =>
Wire s e m (a, c) (b, c) -> s -> a -> c -> m (Either e b, Wire s e m a b)
runLoop wire ts ipt x = do
(result, nextWire) <- stepWire wire ts (Right (ipt, x))
case result of
Left i -> return (Left i, mkEmpty)
Right (value, nextX) ->
return (Right value, mkGen $ \ts' ipt' -> runLoop nextWire ts' ipt' nextX)
in
mkGen $ \ts input -> runLoop loopWire ts input initialValue
Run Code Online (Sandbox Code Playgroud)
在Petr 提供了精彩的答案之后,组合器对于防止组合器发散delay至关重要。只是在上述循环部分中使用下一个值的惰性之间创建一个单值缓冲区。因此,与上述相同的定义是:loopdelaymfixsemiLoop
semiLoop :: (MonadFix m, Monoid s, Monoid e) =>
c -> Wire s e m (a, c) (b, c) -> Wire s e m a b
semiLoop initialValue loopWire = loop $ second (delay initialValue) >>> loopWire
Run Code Online (Sandbox Code Playgroud)