Search code examples
haskellpattern-matchingabstract-data-typepattern-synonyms

Pattern matching Data.Sequence like lists


I am using Data.Sequence instead lists for better performance. With lists we can do the following

foo :: [Int] -> Int
foo [] m = m
foo (x:xs) m = ...

How can this be accomplished with Data.Sequence. I have tried the following:

foo:: S.Seq Int -> Int
foo S.empty m = m
foo (x S.<: xs) m = ...

I think the solution involves using S.viewl and S.viewr, but cannot seem to figure out how.


Solution

  • ViewPatterns is probably the way to go here. Your code doesn't work because you need to call viewl or viewr on your Seq first to get something of type ViewL or ViewR. ViewPatterns can handle that pretty nicely:

    {-# LANGUAGE ViewPatterns #-}
    
    foo (S.viewl -> S.EmptyL)    = ... -- empty on left
    foo (S.viewl -> (x S.:< xs)) = ... -- not empty on left
    

    Which is equivalent to something like:

    foo seq = case S.viewl seq of
        S.EmptyL    -> ...
        (x S.:< xs) -> ...