在haskell中为`_`提供类型签名

nic*_*las 2 haskell

我想联想_coerce但我不能给它一个类型签名。

有什么技巧可以解决这个问题吗?

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
Run Code Online (Sandbox Code Playgroud)

chi*_*chi 7

_是不能重新定义的保留名称。它可以在模式中用作通配符,例如

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

与其他变量名不同,它可以在一个模式中多次出现。

它也可以用作:例如,

let a = _ "hi"
Run Code Online (Sandbox Code Playgroud)

触发特殊错误

• Found hole: _ :: [Char] -> t
  Where: ‘t’ is a rigid type variable bound by
           the inferred type of a :: t
Run Code Online (Sandbox Code Playgroud)

从本质上讲,_ "hi"要求编译器提供一个术语,其类型t应具有使整个表达类型检查时孔_所取代t

因此,您的okesample 并不是真的好,而是触发了上述特殊错误。