2009-12-25 65 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