gpt4 book ai didi

haskell - 了解 Scrap Your Boilerplate 中的 cast 运算符的类型

转载 作者:行者123 更新时间:2023-12-04 18:17:29 24 4
gpt4 key购买 nike

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) 进行比较上述评估为 Just g ,但这似乎不正确。
cast f 的签名在这里发生了什么?

最佳答案

cast的类型是

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

它产生 Nothing如果 xy是不同的类型和 Just argument如果它们相同。请注意,结果类型 y必须从调用上下文中确定 cast用来。如果不是,编译失败并出现 Unresolved 重载/模糊类型变量错误。

在这个特定的例子中,类型是函数类型, (b -> b)为参数, (a -> a)为结果。所以
cast f :: Maybe (a -> a)

mkT也可以写成 mkT = fromMaybe id . cast .

关于haskell - 了解 Scrap Your Boilerplate 中的 cast 运算符的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11375275/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com