繁体   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