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.
For example, x* matches any number of x characters, [0-9]* matches any number of digits, and . * matches any number of anything. A regular expression pattern match succeeds if the pattern matches anywhere in the value being tested.
Pattern matching is a mechanism for checking a value against a pattern. A successful match can also deconstruct a value into its constituent parts. It is a more powerful version of the switch statement in Java and it can likewise be used in place of a series of if/else statements.
Pattern matching is a technique where you test an expression to determine if it has certain characteristics. C# pattern matching provides more concise syntax for testing expressions and taking action when an expression matches.
As of GHC 7.8, you can use pattern synonyms together with view patterns for this purpose:
{-# LANGUAGE ViewPatterns, PatternSynonyms #-}
import qualified Data.Sequence as Seq
pattern Empty <- (Seq.viewl -> Seq.EmptyL)
pattern x :< xs <- (Seq.viewl -> x Seq.:< xs)
pattern xs :> x <- (Seq.viewr -> xs Seq.:> x)
As of GHC 7.10, you can also make it into a bidirectional pattern synonym, so that Empty
, (:<)
and (:>)
can be used as "constructors" as well:
{-# LANGUAGE ViewPatterns, PatternSynonyms #-}
import qualified Data.Sequence as Seq
pattern Empty <- (Seq.viewl -> Seq.EmptyL) where Empty = Seq.empty
pattern x :< xs <- (Seq.viewl -> x Seq.:< xs) where (:<) = (Seq.<|)
pattern xs :> x <- (Seq.viewr -> xs Seq.:> x) where (:>) = (Seq.|>)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With