簡體   English   中英

Haskell無法將預期類型[char]與實際類型IO匹配

[英]Haskell couldn't match expected type [char] with actual type IO

我剛剛開始學習Haskell,但在其他一些錯誤中我一直陷於困境

我正在嘗試使用此代碼遞歸打印字符列表中的所有字符

printall :: [Char] -> [Char]
printall "" = ""
printall (i:is) = if is /= "" then print i else printall is

main = printall "hello world"

但我收到此錯誤,有人可以幫助我嗎?

intro.hs:14:36: error:
• Couldn't match expected type ‘[Char]’ with actual type
‘IO ()’
• In the expression: print i
  In the expression: if is /= "" then print i else printa
ll is
  In an equation for ‘printall’:
      printall (i : is) = if is /= "" then print i else p
 rintall is

intro.hs:16:1: error:
• Couldn't match expected type ‘IO t0’ with actual type ‘
[Char]’

正如您在上面的評論中所述,if子句的每個分支確實應該具有相同的類型。

另外, main函數必須始終具有IO a類型,對於某些a ,通常為() 這意味着printall的類型簽名應為:

printall :: [Char] -> IO ()

與以下內容相同:

printall :: String -> IO ()

print類型為print :: Show a => a -> IO ()

但您的printall類型為printall :: [Char] -> [Char] ,假設它是您想要的。

if x then y else z的表達式需要yz具有相同的類型

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM