giving a type signature to `_` in haskell

Viewed 65

I want to associate _ with coerce yet I can't give a type signature to it.

Is there any trickery to get around that ?

import Data.Coerce

ok :: ()
ok =
  let a = _ "hi"
   in let a :: String = __ "Hi"
       in ()
  where
    _ = undefined
    __ :: Coercible a b => a -> b
    __ = coerce

ko =
  let a = _ "hi"
   in let a :: String = __ "Hi"
       in ()
  where
    __ = undefined
    _ :: Coercible a b => a -> b. -- Invalid type signature: _ :: ... Should be of form <variable> :: <type>parser
    _ = coerce
1 Answers

_ is a reserved name which can not be redefined. It can be used in patterns as a wildcard, e.g.

let (_,x) = ....           -- takes the second component
    (_,_,_,x,_) = ....     -- takes the fourth component
    _ = ....               -- does not bind any variable
in ....

Unlike other variable names, it can appear more than once in a pattern.

It can also be used as a hole: e.g.,

let a = _ "hi"

triggers the special error

• Found hole: _ :: [Char] -> t
  Where: ‘t’ is a rigid type variable bound by
           the inferred type of a :: t

Essentially, _ "hi" asks the compiler to provide which type a term t should have to make the whole expression type-check when hole _ is replaced by t.

Therefore, your ok esample is not really OK, but triggers the above special error.

Related