开发者

Pattern-matching Seq's in Haskell

开发者 https://www.devze.com 2022-12-16 19:50 出处:网络
Pattern matching is one of the most elegant Haskell features. I\'ve been working on a project recently where I need a queue data structure so I\'m using Data.Sequence.However, it looks like I have t

Pattern matching is one of the most elegant Haskell features.

I've been working on a project recently where I need a queue data structure so I'm using Data.Sequence. However, it looks like I have to give up the elegance of pattern matching and resort to guards:

floodFillWorker :: Image -> RGBAColor -> Double -> PixelQueue -> Image
floodFillWorker image base tolerance queue 
    | Seq.null queue = image
    | otherwise      = doSomeWork imag开发者_如何学编程e

Can I use pattern matching with sequences or do I need to use guards?


ephemient is on the right track with view patterns but I think there's a way to do it which is actually quite nice. Data.Sequence was actually written with views in mind and you should use either the ViewL or ViewR types in order to patternmatch on the data structure.

{-# LANGUAGE ViewPatterns #-}

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


You could use view patterns instead of guards, but actually it isn't any better (IMO). The guards look fine to me...

{-# LANGUAGE ViewPatterns #-}

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

精彩评论

暂无评论...
验证码 换一张
取 消