在Haskell上使用Maybe [String]

时间:2015-01-18 19:28:44

标签: 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))'

1 个答案:

答案 0 :(得分:4)

问题来自于尝试执行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 xsMaybe [String]转换为[String],默认为空列表,前置e,然后将其重新包装在Just

作为旁注,您的功能并未涵盖所有可能的情况,如果我要运行verEmails n ((nome, []):xs)会发生什么?甚至是verEmails n ((nome, [Casa 1]):xs)