簡體   English   中英

無法將預期類型`Maybe(String,Int,String)'與實際類型`([Char],t0,[Char])'匹配

[英]Couldn't match expected type `Maybe (String, Int, String)' with actual type `([Char], t0, [Char])'

我正在測試C程序員Haskell教程中的示例(第2部分),並且在這個問題上遇到了一些麻煩....

showPet :: Maybe (String, Int, String) -> String
showPet Nothing     = "none"
showPet (Just (name, age, species)) = "a " ++ species ++ " named " ++ name ++ ", aged " ++ (show age)

在編譯時,使用它進行調用

showPet ("cat",5,"felix")

結果是

<interactive>:131:9:
Couldn't match expected type `Maybe (String, Int, String)'
            with actual type `([Char], t0, [Char])'
In the first argument of `showPet', namely `("cat", 5, "felix")'
In the expression: showPet ("cat", 5, "felix")
In an equation for `it': it = showPet ("cat", 5, "felix")

我是不正確地調用它還是在Haskell中進行了更改,這使得需要進行更改(我已經找到了一些)?

您在showPet類型中showPet ,您的第一個參數應該是showPet :: Maybe (String, Int, String) ,但您只提供了一個(String, Int, String)

你需要在一些Maybe值中“包裝”你的值以使其工作。 對於maybes來說這很容易,因為如果你有一個值,你將永遠只使用JustJust的類型是a -> Maybe a

最終的工作結果是showPet (Just ("cat",5,"felix"))

類型錯誤告訴你showPet期望Maybe something ,但你傳遞的something

在Haskell中, Maybe類型是一個顯式包裝器,它在類型系統中指示值可能不存在。 在運行時缺少由Nothing值表示,並且值的存在需要Just包裝器。

所以你需要用showPet (Just ("cat",5,"felix"))調用showPet showPet (Just ("cat",5,"felix"))

請注意,調用showPet的方式與其定義非常匹配 - 調用的語法與showPet (Just ...的語法匹配showPet (Just ... line。

暫無
暫無

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

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