haskell - 没有因使用 `print' 而产生 (Show a0) 的实例 类型变量 `a0' 不明确

标签 haskell

data NestedList a = Elem a | List [NestedList a]
flatten :: NestedList a -> [a]
flatten (Elem element) = [element]
flatten (List []) = []
flatten (List (first:rest)) = flatten first ++ flatten (List (rest))
main = print $ flatten $ List []

我在haskell中编写了上面看到的代码。例如,当我使用任何其他参数执行此操作时
main = print $ flatten $ List [Elem 1, Elem 2]
main = print $ flatten $ Elem 1

它给
[1, 2]
[1]

分别。

当我用一个空列表执行它时它失败了。
main = print $ flatten $ List []

错误信息
No instance for (Show a0) arising from a use of `print'
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 Show Double -- Defined in `GHC.Float'
  instance Show Float -- Defined in `GHC.Float'
  instance (Integral a, Show a) => Show (GHC.Real.Ratio a)
    -- Defined in `GHC.Real'
  ...plus 23 others
In the expression: print
In the expression: print $ flatten $ List []
In an equation for `main': main = print $ flatten $ List []

问题
  • 为什么它会失败,我该如何解决这个问题?
  • 我应该改变我的NestedList接受空的定义 List ?如果是这样,我该怎么做。它相当困惑。
  • 最佳答案

    列表类型是多态的。由于您不提供元素,因此只提供空列表构造函数 [] ,无法推断这是什么列表类型。

    是:[] :: [Int]
    [] :: [Maybe (Either String Double)] .谁说?

    你是。提供类型注释来解决多态性,然后 GHC 可以分派(dispatch)到正确的显示实例。

    例如。

    main = print $ flatten $ List ([] :: [Int])
    

    关于haskell - 没有因使用 `print' 而产生 (Show a0) 的实例 类型变量 `a0' 不明确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18615666/

    相关文章:

    haskell - 与GHC交叉编译

    haskell - 为什么 Num 不能与 0 进行比较?

    haskell - Pointfree 版本无法编译,但有针对性的版本可以吗?

    haskell - 不理解连接运算符 (++)

    haskell - 如何将每晚的 Haskell 包放入 Stackage LTS?

    algorithm - 在 Haskell 中扩展数独求解器的功能

    haskell - 规范化函数而不在 Haskell 中实际应用它

    haskell - 我可以在 Haskell 中定义参数之间不相等的参数数据类型吗?

    list - 如何修改嵌套自定义数据类型中的列表值?

    haskell - 在 Haskell 中从 IO 中获取元素