哈斯克尔,为什么头和#39;功能还好ghci但无法编译?

时间:2014-06-22 20:04:43

标签: haskell

head' :: [a] -> a
head' [] = error "Cannot call head on emply list."
head' (x:_) = x 

main = do  
    putStrLn  "hello"
    let ret = head' [4,5,6]
    putStrLn ret 

上面的代码,我可以在ghci中加载它并正确调用head'函数。 当我把它放入一个文件并尝试编译它。 IT出错了。 我无法弄清楚为什么会这样。需要帮忙; 感谢。

[1 of 1] Compiling Main             ( head.hs, head.o )

head.hs:7:22:
    No instance for (Num String) arising from the literal `4'
    Possible fix: add an instance declaration for (Num String)
    In the expression: 4
    In the first argument of head', namely `[4, 5, 6]'
    In the expression: head' [4, 5, 6]

1 个答案:

答案 0 :(得分:4)

putStrLn需要String(其类型为putStrLn :: String -> IO ()),而不是数字类型。你想要的是print

    ...
    print ret

print可以采用任何具有Show实例的类型。其类型为print :: Show a => a -> IO ()