2010-01-16 80 views
15

模式匹配是最優雅的Haskell功能之一。Haskell中的模式匹配Seq's

我一直在一個項目最近,我需要一個隊列數據結構,所以我使用Data.Sequence。然而,它看起來像我不得不放棄模式匹配的優雅和訴諸後衛:

floodFillWorker :: Image -> RGBAColor -> Double -> PixelQueue -> Image 
floodFillWorker image base tolerance queue 
    | Seq.null queue = image 
    | otherwise  = doSomeWork image 

我能使用序列模式匹配或者我需要使用看守?

回答

17

ephemient是正確的軌道視圖模式上,但我認爲有辦法做到這一點實際上是相當不錯的。 Data.Sequence實際上是爲了與數據結構匹配而編寫的,並且應該使用ViewLViewR類型來匹配數據結構。

{-# LANGUAGE ViewPatterns #-} 

floodFillWorker image _ _ (Seq.viewl -> EmptyL) = image 
floodFillWorker image base tolerance queue = doSomeWork image 
+0

Thanks!我是否也可以使用它來爲前面和其他模式匹配,如同列表一樣? 例如 floodFillWorker _ _ _(first:rest)= .... – Bill 2010-01-16 17:31:14

+0

我正在考慮指出這一點,但似乎OP實際上並不想在這裏解構序列。但如果這有效,那麼這很好。 – ephemient 2010-01-17 03:05:39

+0

對不起,我原來的問題只有一半。謝謝澄清! – Bill 2010-01-17 04:34:09

6

可能使用view patterns而不是警衛,但實際上它並沒有更好的(國際海事組織)。衛兵們看起來不錯,我...

{-# LANGUAGE ViewPatterns #-} 

floodFillWorker image _ _ (Seq.null -> True) = image 
floodFillWorker image base tolerance queue = doSomeWork image