gpt4 book ai didi

haskell - 在 Haskell 中使用 Maybe [String]

转载 作者:行者123 更新时间:2023-12-05 01:47:19 25 4
gpt4 key购买 nike

我想使用 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)

这是我使用 Maybe 的同一个函数 verEmails:

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 xsMaybe [String] 转换为 [String],默认为空列表,在 e,然后将其包装在 Just 中。

附带说明一下,您的函数并未涵盖所有可能的情况,如果我运行 verEmails n ((nome, []):xs) 会发生什么情况?甚至 verEmails n ((nome, [Casa 1]):xs)

关于haskell - 在 Haskell 中使用 Maybe [String],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28013861/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com