15

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 image

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

2 Answers 2

17

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
3
  • Thanks! Can I also use it to pattern-match for the front and the rest, as I would with a list? e.g. floodFillWorker _ _ _ (first : rest) = ....
    – Bill
    Jan 16, 2010 at 17:31
  • I was considering pointing this out, but it seemed like OP didn't actually want to deconstruct the sequence here. But if that works, then this is good.
    – ephemient
    Jan 17, 2010 at 3:05
  • Sorry, my original question was only half-specified. Thanks for clarifying!
    – Bill
    Jan 17, 2010 at 4:34
6

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.