Question

I'm trying to use Sequences to improve performance. When defining the function below I tried to use the "triangle" operators in pattern patching context.

import qualified Data.Sequence as S

cleanField :: S.Seq Char -> S.Seq Char
cleanField ((S.<|)  ' '  xs) = cleanField xs
cleanField ((S.|>)  xs  ' ') = cleanField xs
cleanField  xs = xs

GHC 7.4.1 says:

seq.hs:4:13: Parse error in pattern: (S.<|)

Can I not use the triangle operators (<|,|>)in pattern matching?

If so, why can I use the cons (:) operator in pattern matching and not the triangle operators?

Was it helpful?

Solution

Xavier Pinho is correct. The operators (<|) and (|>) are ordinary functions, but only data constructors may be used in patterns. (Yes, they're listed in the docs under the title Construction, because they're used to construct sequences out of components, but they're not technically data constructors.)

The library offers two functions viewl and viewr to create members of datatypes ViewL and ViewR. These have constructors :< and :> that can be matched on.

An example:

s :: Seq Int
s = fromList [1,2,3]

test1 :: (Int, Seq Int)
test1 = case viewl s of
          x :< xs -> (x, xs)

test2 :: (Seq Int, Int)
test2 = case viewr s of
          xs :> x -> (xs, x)

The views are also convenient to use with the ViewPatterns language extension. If enabled, you can say

test3 :: Seq Int -> (Int, Seq Int)
test3 (viewl -> x :< xs) = (x, xs)

to match on an incoming sequence as if it was a list.

OTHER TIPS

You can only pattern match on constructors and infix constructors in Haskell have to start with a colon. So those triangle operators are normal functions, : is a list constructor.

To inspect one end of a Sequence, you can use the viewl and viewr functions. These return a ViewL and ViewR, respectively, and these types also have triangle-like operators as constructors. You could use them as follows with pattern guards.

cleanField xs
  | ' '  S.:< rest <- S.viewl xs = cleanField rest
  | rest S.:> ' '  <- S.viewr xs = cleanField rest
  | otherwise                    = xs
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top