简体   繁体   English

在Haskell使用Maybe [String]

[英]Using Maybe [String] at Haskell

i want to return a string using Maybe [String], but i can't manage to do it using Maybe. 我想使用Maybe [String]返回一个字符串,但是我无法使用Maybe做到这一点。

Should i define an instance? 我应该定义一个实例吗?

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)

Here is the same function verEmails, where i use Maybe: 这是相同的功能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)

The error that GHCi gives me: 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))' 

The problem comes from trying to do e : verEmails n xs , since verEmails n xs does not return a list, but a list enclosed in Maybe . 问题来自尝试执行e : verEmails n xs ,因为verEmails n xs不会返回列表,而是返回Maybe中包含的列表。 The easiest way to handle this is to use the Data.Maybe.fromMaybe function: 解决此问题的最简单方法是使用Data.Maybe.fromMaybe函数:

fromMaybe :: a -> Maybe a -> a
fromMaybe onNothing Nothing = onNothing
fromMaybe onNothing (Just a) = a

Here I'm presuming you would want to return Just aList where aList contains all the emails filtered from the Agenda passed in. This means that the only way verEmails will return Nothing is when the agenda passed in is empty. 在这里,我假设您想返回Just aList ,其中aList包含从传入的Agenda筛选出的所有电子邮件。这意味着,当传入的议程为空时, verEmails唯一不会返回Nothing内容的方法。 So we have 所以我们有

verEmails n [] = Nothing
verEmails n ((nome, ((Email e):ls)):xs)
    = if n == nome
        then Just $ e : (fromMaybe [] $ verEmails n xs)
        else verEmails n xs

This just simply converts verEmails n xs from Maybe [String] to [String] , defaulting to the empty list, prepends e , then wraps it back up in a Just . 这只是将verEmails n xsMaybe [String][String] ,默认为空列表,在e加上e ,然后将其包装回Just

As a side note, your function does not cover all possible cases, what happens if I were to run verEmails n ((nome, []):xs) ? 附带说明一下,您的函数无法涵盖所有​​可能的情况,如果我运行verEmails n ((nome, []):xs)会发生什么情况? Or even verEmails n ((nome, [Casa 1]):xs) ? 甚至是verEmails n ((nome, [Casa 1]):xs)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM