作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
Haskell 是否能够指示类型族匹配错误?例如,使用封闭类型族:
type family Testf a where
Testf Char = IO ()
Testf String = IO ()
Testf Int
的类型只是
Testf Int
.编译器不会产生任何类型的错误。如果没有匹配项,是否可以生成一个?
最佳答案
不可能。善良的类型族应用程序不会自己触发错误。相反,当我们尝试使用未简化的类型族表达式时,我们只会得到类型错误。
我们可以使用自定义类型来保存错误消息,以使错误更清晰:
import GHC.TypeLits
data Error (msg :: Symbol) -- a type-level error message
type family Testf a where
Testf Char = IO ()
Testf String = IO ()
Testf x = Error "No match for Testf"
Error msg
时都会打印我们的消息。键入一个未定义的值。
TypeError
以更好的方式打印我们的信息:
{-# language DataKinds #-}
import GHC.TypeLits
type family Testf a where
Testf Char = IO ()
Testf String = IO ()
Testf x = TypeError (Text "No matching case for Testf")
Notes.hs:18:5: error: …
• No matching case for Testf
• In the expression: ...
type T = Testf Int -- this typechecks
x :: T
x = () -- we throw error only here
关于haskell - 如何在 Haskell 中触发类型族模式匹配错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37396378/
我是一名优秀的程序员,十分优秀!