问题描述
代码:
data nestedList a = Elem a | List [nestedList a]
flatten :: nestedList a -> [a]
flatten (Elem e) = [e]
flatten (List l) = foldMap flatten l
main = do
let c0 = List []
print $ flatten c0
当我尝试从main提供空列表时,出现编译器错误:
Ambiguous type variable ‘a0’ arising from a use of ‘print’
prevents the constraint ‘(Show a0)’ from being solved.
Probable fix: use a type annotation to specify what ‘a0’ should be.
非常感谢您的帮助!
解决方法
调用print :: (Show a) => a -> IO ()
时,需要以某种方式解决对Show a
的约束。在您的情况下,推断c0
的类型为NestedList a
,这当然不足以解决来自Show [a]
的{{1}}约束的信息。
您可以通过在print $ flatten c0
的绑定中添加类型签名以使其单态来解决此问题。