haskell - polyTypeOf 很神秘

标签 haskell polymorphism

PolyTypeable是多态类型的 Typeable 的类似物。但它的工作相当不可预测:

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

库源代码很难理解,你能解释一下为什么polyTypeOf接受某些论点而无法接受其他论点,甚至非常相似?

最佳答案

原因与for相同

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

也就是说,ghci 的扩展默认规则允许它解决 Show 的歧义。约束,但不适用于 Enum约束。如果您尝试使用 foo = polyTypeOf show 编译源文件,你也会得到一个模棱两可的类型变量错误(除非你使用 {-# LANGUAGE ExtendedDefaultRules #-} )。

关于haskell - polyTypeOf 很神秘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7947987/

相关文章:

haskell - "monadic application"的更多信息?

haskell - 以区间为键的类似 map 的容器和类似 zip 的组合操作

C++私有(private)多态实现设计

c++ - 跨shared_ptr的dynamic_cast?

c# - 通过扩展方法实现多态性?

haskell - 如何判断一个 monad 是否可交换?

haskell - 使用镜头作为 `map`

C++:结合继承、多态和工厂

haskell - 在 Haskell 中定义一个函数的 2 个或多个方程可以共享相同的 where/let block 吗?

java - 装饰模式困惑?