gpt4 book ai didi

haskell - 区分Haskell中的错误

转载 作者:行者123 更新时间:2023-12-03 07:46:36 25 4
gpt4 key购买 nike

我还是Haskell的新手。区分错误的最佳方法是什么?
目前,我正在使用maybe monad,但它只能“代表一种错误状态”。

以下代码片段将我的问题置于上下文中。

pulOh :: Seq          -- input X O sequence
-> Int -- split point real index
-> Maybe Seq
pulOh xs n =
case (\(f,l)->(tlTrn f, hdTrn l)) (splSq xs n) of -- split and process at index
(Nothing, _) -> Nothing -- first failed
(_, Nothing) -> Nothing -- last failed
(Just f,Just l) -> Just (f ++ l) -- both parts passed

我希望结果能够区分 fstsnd调用是否失败。两者都无法通过 fst失败的情况下进行短路。

最佳答案

使用 Either 。它基本上与带有参数化Maybe构造函数的Nothing相同,换句话说,Maybe aEither () a同构。通过将()“单位错误”替换为自定义的错误标签类型,可以使不同的失败情况有所不同。

pulOh :: Seq -> Int -> Either String Seq
pulOh xs n = case tlTrn *** hdTrn $ splSq xs n of
(Nothing, _) -> Left "first failed"
(_, Nothing) -> Left "last failed"
(Just f,Just l) -> Right $ f ++ l

(我自由地用 *** “并行管道”替换了该lambda)

关于haskell - 区分Haskell中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40911014/

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