我正在閱讀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