为什么是printf "%d\n" 3
模棱两可而不是show 3
?可以printf
重写模块以提供自动消歧吗?大概类似的事情show
必须在printf
...的较低级别完成,或者和之间是否存在一些关键的区别printf
,show
这需要消除数字的歧义?
如果printf
可以重写以自动处理数字而无需明确消歧,那么什么是show
正确的?如何在不消除歧义的show
情况下将数字转换为字符串?:: Int
printf
这是show
(没有任何歧义)的正确操作以及printf
(有歧义)的正确操作:
$ cat printStrLnShow3
import Text.Printf
main = putStrLn (show 3)
$ runghc printStrLnShow3
3
$ cat printfWithInt3
import Text.Printf
main = printf "%d\n" (3 :: Int)
$ runghc printfWithInt3
3
这是不消除数字歧义时的歧义变量错误:printf
$ cat printfWithAmbiguous3
import Text.Printf
main = printf "%d\n" 3
$ runghc printfWithAmbiguous3
printfWithAmbiguous3:2:8:
No instance for (PrintfArg a0) arising from a use of `printf'
The type variable `a0' is ambiguous
Possible fix: add a type signature that fixes these type variable(s)
Note: there are several potential instances:
instance [safe] PrintfArg Char -- Defined in `Text.Printf'
instance [safe] PrintfArg Double -- Defined in `Text.Printf'
instance [safe] PrintfArg Float -- Defined in `Text.Printf'
...plus 12 others
In the expression: printf "%d" 3
In an equation for `main': main = printf "%d" 3
printfWithAmbiguous3:2:22:
No instance for (Num a0) arising from the literal `3'
The type variable `a0' is ambiguous
Possible fix: add a type signature that fixes these type variable(s)
Note: there are several potential instances:
instance Num Double -- Defined in `GHC.Float'
instance Num Float -- Defined in `GHC.Float'
instance Integral a => Num (GHC.Real.Ratio a)
-- Defined in `GHC.Real'
...plus 11 others
In the second argument of `printf', namely `3'
In the expression: printf "%d" 3
In an equation for `main': main = printf "%d" 3