我正在阅读John Hughes的用箭头编程。有一段我实在无法理解的代码。代码如下:Haskell Arrow延迟功能
import Control.Arrow.Operations
import Control.Arrow
import Control.Category
import Prelude hiding ((.),id)
newtype SF a b = SF {runSF :: [a] -> [b]}
instance Category SF where
id = SF id
(.) (SF f) (SF g) = SF $ \x -> f (g x)
(.*.) :: (a -> b) -> (c -> d) -> (a,c) -> (b,d)
(.*.) f g (a,c) = (f a, g c)
instance Arrow SF where
arr f = SF (map f)
first (SF f) = SF (uncurry zip . (f .*. id) . unzip)
instance ArrowLoop SF where
loop (SF f) = SF $ \as -> let (bs,cs) = unzip (f (zip as (stream cs))) in bs
where stream ~(x:xs) = x:stream xs
instance ArrowChoice SF where
left (SF f) = SF (\xs -> combine xs (f [y | Left y <- xs]))
where combine (Left y: xs) (z:zs) = Left z : combine xs zs
combine (Right y :xs) zs = Right y : combine xs zs
combine [] zs = []
instance ArrowCircuit SF where
delay x = SF (x:)
然后
mapA :: ArrowChoice arr => arr a b -> arr [a] [b]
listcase [] = Left()
listcase (x:xs) = Right (x,xs)
mapA f = arr listcase >>>
arr (const []) ||| (f *** mapA f >>> arr (uncurry (:)))
我无法理解的是,
> runSF (mapA (delay 0)) [[1,2,3],[4,5],[6],[7,8],[9,10,11],[12,13,14,15]]
[[0,0,0],[1,2],[4],[6,5],[7,8,3],[9,10,11,0]]
我认为结果应该只是在每个头添加0
因为delay 0
定义为SF (0:)
。
而且更奇怪的,
diag :: (ArrowCircuit a , ArrowChoice a) => a [b] [b]
diag = arr listcase >>>
arr (const []) ||| (arr id *** (diag >>> delay []) >>> arr (uncurry (:)))
runSF diag [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
[[1],[4,2],[7,5,3],[10,8,6]]
我可以看到什么是diag
和mapA (delay 0)
做,但我不是很了解使用delay
计算过程。有人可以帮忙吗?谢谢。
要了解您真正需要了解'ArrowChoice',特别是您未包含在代码中的'ArrowChoice SF'实例。 'mapA'仅适用于具有'ArrowChoice'实例,'mapA :: ArrowChoice a => a b c - > a [b] [c]'的箭头。 'diag'中的'|||'是'Arrow'的'&&&'的'ArrowChoice'类似物。 – Cirdec 2015-02-09 07:10:26
抱歉忽略了ArrowChoice,我添加了它。这对您的评论很有帮助。谢谢〜 – 2015-02-10 00:35:00