Search code examples
haskellabstract-data-type

Why ADT "data MyC c = EmptyC | ConsC c MyC" not type safe?


--This is type safe 
data IntList = Empty | Cons Int IntList
  deriving Show

--This is type safe
data MyB b = EmptyB | ConsB b b
  deriving Show

data MyC c = EmptyC | ConsC c MyC
  deriving Show

Why is abstract data type MyC not type safe ? The gaurd clause ConsC c MyC should construct the Cons list as it is invokding MyC in same way that IntList is invoked from Cons Int IntList for IntList ADT ?


Solution

  • This is not valid, it has nothing to do with safety, it is simply incorrect.

    data MyC c = EmptyC | ConsC c MyC
    

    The problem here is that MyC takes an argument, but when it is used, it is not given an argument. It should be as follows:

    data MyC c = EmptyC | ConsC c (MyC c)
    --                            ^^^^^^^ The parameter is necessary
    

    Note that MyC Int is basically the same as IntList.