haskell - 了解废弃您的样板中强制转换运算符的类型

标签 haskell scrap-your-boilerplate

2003年Scrap Your Boilerplate paper由 Laemmel 和 SPJ 编写,第 3 页有一个代码片段

mkT :: (Typeable a, Typeable b) => (b -> b) -> a -> a
mkT f = case cast f of
   Just g -> g
   Nothing -> id

然后论文解释了

That is, mkT f x applies f to x if x's type is the same as f's argument type

按照本文前面示例的模式,我认为 cast f 的类型必须与 Maybe (b -> b) 类型进行比较code> 上面的计算结果为 Just g,但这似乎不正确。

cast f 的签名是怎么回事?

最佳答案

cast的类型是

cast :: (Typeable x, Typeable y) => x -> Maybe y

如果xy是不同类型,它会产生Nothing;如果它们相同,它会产生Just argument。请注意,使用 cast 时,结果类型 y 必须由调用上下文确定。如果不是,编译将失败,并出现 Unresolved 重载/不明确的类型变量错误。

在此特定示例中,类型是函数类型,(b -> b) 表示参数,(a -> a) 表示结果。所以

cast f :: Maybe (a -> a)

mkT也可以写成mkT = fromMaybe id。类型转换

关于haskell - 了解废弃您的样板中强制转换运算符的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11375275/

相关文章:

f# - 在 f# 中废弃你的样板

haskell - 如何在 Haskell 中泛化输入

list - Common Lisp 相当于 Haskell 的副本?

haskell - 从类型 `T a` 转换为 `T b`,无需样板

haskell - 是否可以使用 SYB 转换类型?

haskell - Haskell中AST的无样板注释?

haskell - 自由 monad 和类型约束

haskell - 如何在 GHCi 中定义数据类型

haskell - 网络斯科蒂 : file not found while serving static files