Why does this view pattern fail when using Data.Sequence?

I have a program which is something like this:

import System.Random
import Data.Sequence (Seq(..), ViewL(..))
import qualified Data.Sequence as Seq

filterGap :: Int -> [Bool] -> [Bool]
filterGap n = go (Seq.replicate n False)
    where
        go :: Seq Bool -> [Bool] -> [Bool]
        go _ [] = []
        go (Seq.viewl -> (True :< rest)) (True:xs) = False : go (rest :|> False) xs
        go (Seq.viewl -> (False :< rest)) (x: xs) = x : go (rest :|> x) xs
        go x y = error $ "filterGap: " ++ show x ++ " " ++ show (take 3 y)

gapAB :: Int -> Int -> IO String
gapAB gapsize length = take length . map toAB . filterGap gapsize .  randoms <$> newStdGen
    where
        toAB b = if b then 'b' else 'a'

But I sometimes get this kind of errors

ghci> gapAB 3 100
"baaabbbaaaabba*** Exception: filterGap: fromList [True,True,False] [False,False,True]
CallStack (from HasCallStack):
  error, called at bench/ReBench/Bench.hs:32:18 in main:ReBench.Bench

I am surprised why this is happening. The last pattern should never be triggered, right? Also, from the error, we can see that the sequence is not empty.

1 Like

The arguments are fromList [True,True,False] and [False,False,True]. It doesn’t match

  • go _ [] = [] because the list is not empty
  • go (Seq.viewl -> (True :< rest)) (True:xs) because the list doesn’t start with True
  • go (Seq.viewl -> (False :< rest)) (x: xs) because the Seq doesn’t start with False

So yes, seems like the last pattern should be triggered.

3 Likes

You are right. That was silly.