2009-12-25 66 views
4

示例代码:Haskell的类型转换问题

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 

回答

25

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

(((putStrLn show) fac) 10) 

你给show作为putStrLn的参数,这是错误的,因为show是fu nction和putStrLn需要一个字符串。你希望它是这样的:

putStrLn (show (fac 10)) 

你既可以加上括号它这样,也可以使用$操作,基本上parenthesizes一切,它的右边:

putStrLn $ show $ fac 10 
+1

+1' $'是你的朋友。 – 2009-12-25 07:43:17

+0

($)和(。)是你爱的朋友<3 – codebliss 2009-12-25 16:42:47