In the following code, I'm trying to match on the GADT constructor Cons
to get the compiler to see that xs
is non-empty:
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeOperators #-}
import Data.Typeable
data Foo (ts :: [*]) where
Nil :: Foo '[]
Cons :: (Typeable t) => Foo ts -> Foo ( t ': ts)
foo :: Foo xs -> IO ()
foo Nil = print "done"
foo (Cons rest :: Foo (y ': ys)) = do
print $ show $ typeRep (Proxy::Proxy y)
foo rest
Unfortunately, this simple example fails to compile with GHC 8:
• Couldn't match type ‘xs’ with ‘y : ys’
‘xs’ is a rigid type variable bound by
the type signature for:
foo :: forall (xs :: [*]). Foo xs -> IO ()
Expected type: Foo (y : ys)
Actual type: Foo xs
• When checking that the pattern signature: Foo (y : ys)
fits the type of its context: Foo xs
In the pattern: Cons rest :: Foo (y : ys)
In an equation for ‘foo’:
foo (Cons rest :: Foo (y : ys))
= print $ (show $ typeRep (Proxy :: Proxy y))
I know that type inference can be tricky with GADTs (e.g., #9695, #10195, #10338), but this is so simple...
What do I need to do to convince GHC that when I match on Cons
, the GADT argument has at least one element?
foo :: Foo (x ': xs) -> ()
? – Alecfoo
really has some recursive calls in it. I need to match on either theCons
case or theNil
case (elided), and naturallyNil :: Foo '[]
. I really do need GHC to figure outxs ~ (y ': ys)
based on the pattern match. – crockeea