gpt4 book ai didi

class - Haskell 类型系统的细微差别

转载 作者:行者123 更新时间:2023-12-03 23:59:48 25 4
gpt4 key购买 nike

我一直在深入了解 haskell 类型系统的本质,并试图了解类型类的精髓。我已经学会了一堆,但是我在下面的代码中遇到了困难。

使用这些类和实例定义:

class Show a => C a where
f :: Int -> a

instance C Integer where
f x = 1

instance C Char where
f x = if x < 10 then 'c' else 'd'

为什么这会通过类型检查器:
g :: C a => a -> Int -> a
g x y = f y

yes :: C a => a -> Int -> String
yes x y = show (g x y)

但这不是吗?
g :: C a => a -> Int -> String
g x y = show(f y)

我发现第二种选择更具可读性,它似乎只是一个很小的区别(注意类型签名)。但是,试图通过类型检查器会导致:
*Main> :l typetests.hs
[1 of 1] Compiling Main ( typetests.hs, interpreted )

typetests.hs:11:14:
Ambiguous type variable `a0' in the constraints:
(C a0) arising from a use of `f' at typetests.hs:11:14
(Show a0) arising from a use of `show' at typetests.hs:11:9-12
Probable fix: add a type signature that fixes these type variable(s)
In the first argument of `show', namely `(f y)'
In the expression: show (f y)
In an equation for `g': g x y = show (f y)
Failed, modules loaded: none.

我不明白为什么。

注意:请不要问“你想做什么?”我希望很明显,我只是在一个抽象的上下文中乱搞,以探索这种语言的工作方式。除了学习新东西,我没有其他目标。

谢谢

最佳答案

这是一个有趣的玩具发挥作用的地方。考虑标准 Prelude 函数 asTypeOf .

asTypeOf :: a -> a -> a
asTypeOf = const

它只返回它的第一个参数,不管第二个参数是什么。但是它上面的类型签名附加了一个约束,即它的两个参数必须是相同的类型。
g :: C a => a -> Int -> String
g x y = show (f y `asTypeOf` x)

现在,GHC 知道 f y 的类型是什么是。与 g 的第一个参数的类型相同.如果没有这些信息,那么您会收到您看到的错误消息。只是没有足够的信息来确定 f y 的类型。 .而且因为类型很重要(它用于确定 show 使用哪个实例),所以 GHC 需要知道生成代码的意思是什么类型。

关于class - Haskell 类型系统的细微差别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7074322/

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