[英]Using Maybe [String] at Haskell
我想使用Maybe [String]返回一个字符串,但是我无法使用Maybe做到这一点。
我应该定义一个实例吗?
data Contacto = Casa Integer
| Trab Integer
| Tlm Integer
| Email String
deriving (Show)
type Nome = String
type Agenda = [(Nome, [Contacto])]
addEmail :: Nome -> String -> Agenda -> Agenda
addEmail n email agenda = (n, [Email email]):(agenda)
verEmails :: Nome -> Agenda -> [String]
verEmails n [] = []
verEmails n ((nome, ((Email e):ls)):xs) = if n == nome then (e:(verEmails n xs))
else (verEmails n xs)
这是相同的功能verEmails,我在其中使用Maybe:
verEmails :: Nome -> Agenda -> Maybe [String]
verEmails n [] = Nothing
verEmails n ((nome, ((Email e):ls)):xs) = if n == nome then Just (e:(verEmails n xs))
else (verEmails n xs)
GHCi给我的错误是:
Couldn't match expected type `[String]' with actual type `Maybe [String]' In the return type of a call of `verEmails' In the second argument of `(:)', namely `(verEmails n xs)' In the first argument of `Just', namely `(e : (verEmails n xs))'
问题来自尝试执行e : verEmails n xs
,因为verEmails n xs
不会返回列表,而是返回Maybe
中包含的列表。 解决此问题的最简单方法是使用Data.Maybe.fromMaybe
函数:
fromMaybe :: a -> Maybe a -> a
fromMaybe onNothing Nothing = onNothing
fromMaybe onNothing (Just a) = a
在这里,我假设您想返回Just aList
,其中aList
包含从传入的Agenda
筛选出的所有电子邮件。这意味着,当传入的议程为空时, verEmails
唯一不会返回Nothing
内容的方法。 所以我们有
verEmails n [] = Nothing
verEmails n ((nome, ((Email e):ls)):xs)
= if n == nome
then Just $ e : (fromMaybe [] $ verEmails n xs)
else verEmails n xs
这只是将verEmails n xs
从Maybe [String]
为[String]
,默认为空列表,在e
加上e
,然后将其包装回Just
。
附带说明一下,您的函数无法涵盖所有可能的情况,如果我运行verEmails n ((nome, []):xs)
会发生什么情况? 甚至是verEmails n ((nome, [Casa 1]):xs)
?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.