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
吗?如果是这样,我该怎么做。它相当混乱。