View patterns

2019-01-23

I’m learning about the GHC ViewPatterns language extension at the same time as learning about Data.Sequence. I like the the ability to pattern-match on sequences a lot. Unfortunately, it looks like the exhaustiveness checker cannot detect when all possible patterns are covered. Here’s an example:

#!/usr/bin/env stack
{- stack --resolver=lts-12.6 script -}
{-# LANGUAGE ViewPatterns #-}
{-# OPTIONS_GHC -Wall #-}
import Data.Sequence
import qualified Data.Sequence as Seq
joinShow :: Show a => Seq a -> String
joinShow (viewl -> EmptyL) = ""
joinShow (viewl -> x :< xs) = show x ++ joinShow xs
main :: IO ()
main = do
let xs = Seq.fromList [1 :: Int, 2, 3, 4]
print $ joinShow xs
{-
/path/to/ViewPatternDemo.hs:11:1: warning: [-Wincomplete-patterns]
Pattern match(es) are non-exhaustive
In an equation for ‘joinShow’: Patterns not matched: _
|
11 | joinShow (viewl -> EmptyL) = ""
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^...
-}

Running this script results in the following compiler warnings:

/path/to/ViewPatternDemo.hs:11:1: warning: [-Wincomplete-patterns]
    Pattern match(es) are non-exhaustive
    In an equation for ‘joinShow’: Patterns not matched: _
   |
11 | joinShow (viewl -> EmptyL) = ""
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^...
-}

I’m going to see if there are known GHC bugs related to this issue.

Update: 2019-01-25

It turns out that the PatternSynonyms language extension can do more or less the same thing but with nicer syntax:

#!/usr/bin/env stack
{- stack --resolver=lts-12.6 script -}
{-# OPTIONS_GHC -Wall #-}
import Data.Sequence
import qualified Data.Sequence as Seq
joinShow :: Show a => Seq a -> String
joinShow Empty = ""
joinShow (x :<| xs) = show x ++ joinShow xs
main :: IO ()
main = do
let xs = Seq.fromList [1 :: Int, 2, 3, 4]
print $ joinShow xs

I think pattern synonyms are strictly less powerful than view patterns which is why (I think) GHC’s exhaustiveness checker works better with them.

Related posts

oset-0.4.0.1 released
Alternative newtype wrappers for oset
New packages
oset

Tags

Haskell
GHC
View patterns
Pattern synonyms
oset

Content © 2025 Richard Cook. All rights reserved.