我只是想在Haskell中编写我能想象到的最简单的函数,并得到了这个错误信息。奇怪的是,当我尝试评估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)
答案 0 :(得分:9)
$array = explode(",","3,4,5");
if (in_array(3, $array)) {
echo 'in array';
} else {
echo 'not in array';
没有任何问题,如果使用的话,你会遇到同样的问题:
myHead
此处的问题是main = do
print Nothing
和Nothing
对于任何myHead []
都具有多态类型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