gpt4 book ai didi

haskell - 错误处理和单子(monad)?

转载 作者:行者123 更新时间:2023-12-03 07:45:17 24 4
gpt4 key购买 nike

我正在尝试了解如何应用 Haskel 的 Maybe-idiom .. 我正在阅读 http://en.wikibooks.org/wiki/Haskell/Understanding_monads/Maybe这表明在字典中查找可能会返回 Maybe并且该值通过 >>= 传播运算符(operator)。

来自 URL 的示例:

如果我们想在第三次查询中使用政府数据库查询的结果(比如我们想查询他们的注册号,看看他们是否欠任何汽车税),那么我们可以扩展我们的 getRegistrationNumber 函数:

getTaxOwed :: String       -- their name
-> Maybe Double -- the amount of tax they owe
getTaxOwed name =
lookup name phonebook >>=
(\number -> lookup number governmentalDatabase) >>=
(\registration -> lookup registration taxDatabase)

或者,使用 do-block 样式:
getTaxOwed name = do
number <- lookup name phonebook
registration <- lookup number governmentalDatabase
lookup registration taxDatabase

问题:

我如何处理错误处理?我认为大多数代码将受益于告诉哪里出了问题。而不是仅仅报告“在电话簿或政府数据库中找不到 John Doe”,它应该报告哪个资源有问题。

最佳答案

您可以将 monad 实例用于 Either String , 本质上定义为

instance Monad (Either String) where                                             
fail msg = Left msg
return x = Right x

Left msg >>= k = Left msg
Right x >>= k = k x

(实际的定义要复杂一些。)

如果我们将字典定义为由标签和查找表组成的对
type Dict a b = (String, [(a, b)])

phonebook' :: Dict String Int
phonebook' = ("phone book", phonebook)

governmentalDatabase' :: Dict Int Int
governmentalDatabase' = ("governmental database", governmentalDatabase)

taxDatabase' :: Dict Int Double
taxDatabase' = ("tax database", taxDatabase)

在哪里 phonebook , governmentalDatabase , 和 taxDatabase正如你之前定义的那样,我们可以使用另一种单子(monad)查找函数,它在 Either String 中返回结果。 -单子(monad):
lookup' :: (Eq a, Show a) => a -> Dict a b -> Either String b
lookup' key (descr, table) = case lookup key table of
Nothing -> Left ("couldn't find " ++ show key ++ " in " ++ descr)
Just val -> Right val

说明 monad 的强大功能,现在唯一需要在客户端函数中更改的是类型签名:
getTaxOwed :: String               -- their name                                 
-> Either String Double -- either an error message
-- or the amount of tax they owe
getTaxOwed name = do
number <- lookup' name phonebook'
registration <- lookup' number governmentalDatabase'
lookup' registration taxDatabase'

在未知名称上运行此函数会给出:
> getTaxOwed "Joe"
Left "couldn't find \"Joe\" in phone book"

关于haskell - 错误处理和单子(monad)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11931324/

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