未键入空列表:Haskell

Not typed empty list : Haskell

我只是试图在 Haskell 中编写我能想象到的最简单的 maybe 函数,但收到此错误消息。神奇的是,它只出现在我尝试为空列表评估 myHead 时。我做错了什么?

module Main 
  where

myHead :: [a] -> Maybe a
myHead [] = Nothing
myHead (x:_) = Just x

main = do
print (myHead [])

当我从文件中 运行 时,我得到了这个输出:

main.hs:15:1: error:
  • 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.
 These potential instances exist:
   instance Show Ordering -- Defined in ‘GHC.Show’
   instance Show Integer -- Defined in ‘GHC.Show’
   instance Show a => Show (Maybe a) -- Defined in ‘GHC.Show’
    ... plus 22 others
     ...plus 12 instances involving out-of-scope types
    (use -fprint-potential-instances to see them all)
 • In a stmt of a 'do' block: print (myHead [])
  In the expression: do { print (myHead []) }
  In an equation for ‘main’: main = do { print (myHead []) }
  <interactive>:3:1: error:
   • Variable not in scope: main
   • Perhaps you meant ‘min’ (imported from Prelude)

myHead没有问题,如果你使用:

也会有同样的问题
main = do
   print Nothing

这里的问题是 NothingmyHead [] 具有多态类型 Maybe a,对于任何 a。然后,调用 print 写入该值。为此,print 必须要求 Maybe a 可转换为字符串:它通过要求 Show (Maybe a) 来做到这一点,而这又需要 Show a.

但是,没有 Show a 的通用实例:编译器现在需要知道 a 是什么,然后才能将其转换为字符串。

注意这个

print (Just 3 :: Maybe Int) -- OK
print (Just id :: Maybe (Int->Int)) -- Not OK! Functions can not be printed

解决方案是为您的代码使用具体类型

main = do
   print (myHead [] :: Maybe Int) -- or any other showable type