我正在尝试编写一个扁平化嵌套列表的函数。
编码:
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]
来自 print $ flatten c0
的约束.
您可以通过将类型签名添加到 c0
的绑定(bind)来解决此问题。使其具有单态性。
关于list - 空列表上的 foldMap 时 Haskell 模棱两可的类型变量编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63865567/