![](/img/trans.png)
[英]Haskell IO return Couldn't match type ‘[Char]’ with ‘Char’ Expected type: String Actual type: [String]
[英]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
的表達式需要y
和z
具有相同的類型
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.