Why can't I redefine the : operator in Haskell

2019-07-31 12:30发布

问题:

I'm trying to reimplement some functionality of the list data type in Haskell for learning purposes. When I try to redefine : with this code:

{-# LANGUAGE NoImplicitPrelude #-}

data List a = Nil
            | Cons a (List a)

(:) :: a -> List a -> List a
(:) = Cons

I get the following error with stack runghc:

Invalid type signature: (:) :: ...

Should be of form <variable> :: <type>

Is it impossible to redefine :? Is that why I'm getting this error?

回答1:

It is impossible to redefine :, but that is not why you are getting that error. You are getting that error because : is considered "upper-case punctuation" -- that is, any name that starts with : must be an (infix) value constructor. Nevertheless, even with NoImplicitPrelude and RebindableSyntax turned on, you will find that, e.g.

data Foo = Foo : Foo

gives you an error, saying:

error: Illegal binding of built-in syntax: :

Presumably with some extra engineering effort, a future GHC could support redefining : with some suitable extensions turned on, but for now it's not possible.