2014-01-05 139 views
0

有人可以請解釋我的函數中發生了什麼。無法與實際類型'IO [Int]'匹配預期類型`Int'

arrayReader :: [Int] -> IO [Int] 
arrayReader arr = do 
    item <- readLn 
    return $ if item == 0 
      then arr 
      else arrayReader item:arr 

但Haskell是不愉快的6號線:

reader.hs:6:17: 
    Couldn't match expected type `Int' with actual type `IO [Int]' 
    In the return type of a call of `arrayReader' 
    In the first argument of `(:)', namely `arrayReader item' 
    In the expression: arrayReader item : arr 

有人能解釋什麼需要改變,使這個功能編譯?

回答

2

首先,你有一個優先錯誤 - arrayReader item:arr解析爲(arrayReader item):arr。你需要寫arrayReader (item:arr)

其次,arrayReader產生IO [Int]類型的東西,但在這種情況下return需要[Int]類型的東西,產生IO [Int]。您需要重新排列代碼,以便只在arr上調用return,而不是arrayReader的結果。

+0

感謝您的第一個提示。第二個:我需要arrayReader的結果.. – mgoszcz2

+0

你不必使用'return'來產生一個結果 - 只要調用產生結果的東西作爲你做的「最後一件事」就會返回你自己的結果呼叫者。 –

+0

換句話說,不要'返回$ if ...',而是使用'if ...'和'然後返回arr'。 –

相關問題