2017-04-25 34 views
1

在下面的代碼中,我試圖顯示factorial(整數)的結果。我收到以下錯誤消息,我想知道發生了什麼以及爲什麼。謝謝!在if-else語句中無法顯示/打印int

factorial2 0 = 1 
factorial2 n = n * factorial2 (n-1) 

main = do putStrLn "What is 5! ?" 
     x <- readLn 
     if x == factorial2 5 
      then putStrLn "Right" 
      -- else print factorial2 5 -- why can't pass here 
      -- else show factorial2 5 -- why can't pass here 
      else putStrLn "Wrong" -- this can pass, no problem 

-- Factorial.hs:10:20: 
--  Couldn't match expected type ‘Integer -> IO()’ 
--     with actual type ‘IO()’ 
--  The function ‘print’ is applied to two arguments, 
--  but its type ‘(a0 -> a0) -> IO()’ has only one 
--  In the expression: print factorial2 5 
--  In a stmt of a 'do' block: 
--  if x == factorial2 5 then putStrLn "Right" else print factorial2 5 
-- Failed, modules loaded: none. 

回答

3

Haskell函數應用程序是關聯的。這意味着當你打電話給print factorial2 5時,haskell會解釋它,因爲你傳遞了兩個參數來打印:factorial25,但打印只需要一個參數。如果你的代碼是另一種語言,它將相當於:print(factorial2, 5)

原因show factorial2 5不起作用,因爲你的do塊中的所有內容都需要返回一個IO(),但是show factorial2 5返回一個字符串。

只需print (factorial2 5)將工作,以便haskell知道您想要將factorial2 5的結果傳遞給print

+1

我會說Haskell(函數應用程序)是* left * associative:'print factorial2 5'與'(print factorial2)5'相同。 –

+0

@DavidYoung感謝你是完全正確的,讓我的左右混合了哈哈。編輯我的帖子。 –

0

功能顯示的類型爲:a -> String。 所以它需要一個參數並將其轉換爲一個字符串。

在你行

else show factorial2 5 -- why can't pass here 

你給論點,即factorial2和。

你必須給一個函數參數顯示,在你的案件factorial2 5的結果。因此你必須把factorial2 5到括號:

else show (factorial2 5) 

你經常會看到$運營商:

else show $ factorial2 5 

它允許您保存括號。