Search code examples
haskellvectorpattern-synonyms

Haskell pattern matching on vectors


Is it possible to use list style pattern matching on vectors?

ie

import qualified Data.Vector as V

f :: V.Vector a -> a
f (x:xs) = x 

gives an error


Solution

  • -XViewPatterns can let you do this:

    {-# LANGUAGE ViewPatterns #-}
    module VecViewPats where
    
    import Data.Vector (Vector)
    import qualified Data.Vector as V
    
    uncons :: Vector a -> Maybe (a, Vector a)
    uncons v = if V.null v
      then Nothing
      else Just (V.unsafeHead v, V.unsafeTail v)
    
    vsum :: Num a => Vector a -> a
    vsum (uncons -> Just (a,av)) = a + vsum av
    vsum (uncons -> Nothing) = 0
    

    Or -XLambdaCase

    import Control.Category ((>>>))
    -- ...
    vsum :: Num a => Vector a -> a
    vsum = uncons >>> \case
      Just (a,av) -> a + vsum av
      Nothing     -> 0
    

    But honestly, that's seems like a bit of a code smell as you're using one data structure (Vector) as another ([]) which suggests that maybe your choice of data structure is off.

    If you really just want to treat it like a list for the purposes of some algorithm, why not use toList?