17

Today I started to learn about GADTs from: haskell.org and https://wiki.haskell.org

Unfortunately, I don't know how to use them. If I run the code from the example I get the following error:

[1 of 1] Compiling Main             ( test.hs, interpreted )

AFP_229.hs:31:1:
Illegal generalised algebraic data declaration for `Term'
  (Use GADTs to allow GADTs)
In the data declaration for `Term'
Failed, modules loaded: none.
Prelude>

This is the code I am using:

data Term a where
  Lit    :: Int -> Term Int
  Succ   :: Term Int -> Term Int
  IsZero :: Term Int -> Term Bool   
  If     :: Term Bool -> Term a -> Term a -> Term a
  Pair   :: Term a -> Term b -> Term (a,b)

I have tried other sample code, but this gives me the same error. How do you allow GADTs?

maffh
  • 299
  • 3
  • 12

1 Answers1

25

The Use GADTS to allow GADTS looks wild :)

Basically there are two ways to enable language extensions:

  • path a -X<extensions> to ghc, e.g. ghc -XGADTS

  • put {-# LANGUAGE <extension> #-} at the top of a file, e.g. {-# LANGUAGE GADTs #-}

Initially the error messages looked like that: Use -XGADTs to allow GADTs, but actually language pragma (the second way) is more common, and people started complaining that it is hard to copy-n-paste extension name from the error message, so -X was dropped.

Anton Xue
  • 813
  • 11
  • 25
Yuras
  • 13,856
  • 1
  • 45
  • 58
  • 9
    The `{-# LANGUAGE GADTs #-}` approach is pretty much always the way to go, because it lets people reading the source see immediately what extensions are in play. – dfeuer Sep 28 '15 at 17:26
  • @dfeuer I agree. Actually that is why it is more common. – Yuras Sep 28 '15 at 17:28
  • Thank you for your help. – maffh Sep 28 '15 at 17:29
  • There is also the option of `{-# OPTIONS_GHC -XGADTs #-}`, but that's less readable, so I'd go with a `LANUGAGE` pragma by default, too. – AJF Sep 28 '15 at 19:55