haskell - 在 haskell 中给 `_` 一个类型签名

标签 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

最佳答案

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

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

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

它也可以用作:例如,

let a = _ "hi"

触发特殊错误

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

本质上,_ "hi" 要求编译器提供术语 t 应该在 hole _< 时对整个表达式进行类型检查的类型 替换为 t

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

关于haskell - 在 haskell 中给 `_` 一个类型签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67572802/

相关文章:

haskell - 如何为有文化的 Haskell 编程设置 vim 缩进?

haskell - 如何使用 Maybe 的镜头设置功能?

haskell - Haskell 中的部分应用程序内存管理

list - 列表的 'maximum' 函数是否只能在单独的函数中工作?

haskell - 你能在 Haskell 中部分约束一个类型吗?

haskell - 为什么没有函数的 Show 实例?

haskell - 使用 Void 的实际例子

haskell - 为什么 'Alternative' 没有 'Control.Applicative.Const' 实例

haskell - 函数似乎在常量空间内工作,但常量空间太多了

haskell - 良好的 Haskell 编码标准