gpt4 book ai didi

haskell - 'show'在Haskell中是如何实现的?

转载 作者:行者123 更新时间:2023-12-02 21:21:12 24 4
gpt4 key购买 nike

我试图了解类型系统在 Haskell 中的工作原理。

class (Show a) => MyShow a where 
myShow :: a -> String

instance MyShow Integer where
myShow = show

myshow :: (Show a) => a -> String
myshow = show

main = do
putStrLn $ myshow 1
putStrLn $ myShow (2 :: Integer) -- why do I need '::Integer' here?

为什么“myshow 1”在没有类型的情况下也能工作,而“myShow 2”在没有显式类型的情况下会导致错误:

Ambiguous type variable `a0' in the constraints:
(MyShow a0) arising from a use of `myShow'
at nooverinst.hs:12:16-21
(Num a0) arising from the literal `2' at nooverinst.hs:12:23
Probable fix: add a type signature that fixes these type variable(s)
In the second argument of `($)', namely `myShow 2'
In the expression: putStrLn $ myShow 2
In the expression:
do { putStrLn $ myshow 1;
putStrLn $ myShow 2 }

同样奇怪的是,使用GHCI时没有错误:

*Main> myShow 2
"2"

那么,在这种情况下,“myshow”和“myShow”有什么区别?它们都被定义为与“show”相同。我错过了什么?

更新:

答案摘要:这种行为与违约有关。事实上,“show 1”和“myshow 1”工作是一种特殊情况(请参阅 Haskell report section on defaulting )。在源代码顶部添加“default ()”会关闭默认设置,并导致代码在“myshow 1”处中断,因为类型歧义不再通过默认设置来解决。因此,事实上,两行 putStrLn 行都应该在末尾有类型签名。

感谢所有回答的人!

最佳答案

这与默认(Haskell 标准的阴暗角落之一)有关,如 http://www.haskell.org/onlinereport/haskell2010/haskellch4.html#x10-790004.3.4 中所述。

简而言之,Haskell 以一种特殊的方式对待数字类,并自动默认在数字类上出现的歧义,但涉及的其他约束是基类。从这个意义上说,Show 也是特殊的,并且您自己定义的 MyShow 会以不同的方式处理。

在 GHCi 中,扩展的默认规则生效,稍微放宽了限制。这些在http://www.haskell.org/ghc/docs/latest/html/users_guide/interactive-evaluation.html#extended-default-rules中有描述。

关于haskell - 'show'在Haskell中是如何实现的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12167786/

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