polyTypeOf很神秘

mod*_*lar 6 polymorphism haskell

PolyTypeableTypeable的类比,用于多态类型.但它的作用相当不可预测:

ghci> :t show
show :: Show a => a -> String
ghci> polyTypeOf show
a1 -> [Char]
ghci> :t fromEnum 
fromEnum :: Enum a => a -> Int
ghci> polyTypeOf fromEnum 

<interactive>:1:12:
    Ambiguous type variable `a0' in the constraint:
      (Enum a0) arising from a use of `fromEnum'
    Probable fix: add a type signature that fixes these type variable(s)
    In the first argument of `polyTypeOf', namely `fromEnum'
    In the expression: polyTypeOf fromEnum
    In an equation for `it': it = polyTypeOf fromEnum
Run Code Online (Sandbox Code Playgroud)

库源代码很难理解,你能解释为什么polyTypeOf接受某些参数并且不能接受其他参数,甚至非常相似吗?

Dan*_*her 7

原因与之相同

Prelude> show undefined
"*** Exception: Prelude.undefined
Prelude> fromEnum undefined

<interactive>:0:1:
    Ambiguous type variable `a0' in the constraint:
      (Enum a0) arising from a use of `fromEnum'
    Probable fix: add a type signature that fixes these type variable(s)
    In the expression: fromEnum undefined
    In an equation for `it': it = fromEnum undefined
Run Code Online (Sandbox Code Playgroud)

也就是说,ghci的扩展默认规则允许它解决Show约束的歧义,但不能解决约束的歧义Enum.如果您尝试使用编译源文件foo = polyTypeOf show,则还会出现模糊的类型变量错误(除非您使用{-# LANGUAGE ExtendedDefaultRules #-}).