Skip to content

Instantly share code, notes, and snippets.

@L-TChen
Last active June 30, 2023 13:42
Show Gist options
  • Save L-TChen/4c0dc8d270d2b14ee23b392717c91a38 to your computer and use it in GitHub Desktop.
Save L-TChen/4c0dc8d270d2b14ee23b392717c91a38 to your computer and use it in GitHub Desktop.
Pattern matching for Vector using PatternSynonyms in Haskell
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE PatternSynonyms #-}
import Data.Vector as V
pattern Empty :: Vector a
pattern Empty <- (V.null -> True) where Empty = V.empty
uncons :: Vector a -> Maybe (a, Vector a)
uncons Empty = Nothing
uncons v = Just (unsafeHead v, unsafeTail v)
pattern (:<|) :: a -> Vector a -> Vector a
pattern x :<| xs <- (uncons -> Just (x, xs))
pattern (:|>) :: Vector a -> a -> Vector a
pattern xs :|> x <- (unsnoc -> Just (xs, x))
vsum :: Num a => Vector a -> a
vsum Empty = 0
vsum (x :|> xs) = x + vsum xs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment