Haskell类型转换问题

时间:2009-12-25 06:53:24

标签: haskell casting types

示例代码:

fac :: Int → Int
fac 0 = 1
fac n = n * fac (n-1)

main = do
        putStrLn show fac 10

错误:

Couldnt match expected type 'String'
       against inferred type 'a -> String'
In the first argument of 'putStrLn', namely 'show'
In the expression: putStrLn show fac 10

1 个答案:

答案 0 :(得分:25)

让我们添加括号来显示如何实际解析此代码:

(((putStrLn show) fac) 10)

您将show作为putStrLn的参数,这是错误的,因为show是一个函数而putStrLn需要一个字符串。你希望它是这样的:

putStrLn (show (fac 10))

你可以像这样用括号括起来,或者你可以使用$运算符,它基本上将其右边的所有内容括起来:

putStrLn $ show $ fac 10