首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >可扩展错误

可扩展错误
EN

Stack Overflow用户
提问于 2013-07-10 12:33:27
回答 1查看 110关注 0票数 1

用几个单词描述一个问题。我想我有一个算法来检查一些东西,根据算法的不同,它可能会失败,并出现略有不同的错误,例如:

代码语言:javascript
复制
data Error1 = Error1
data Error2 = Error2
data Error3 = Error3

class Algorithm a where
    type CanFailWith a :: *
    check :: Something -> Maybe (CanFailWith a)

instance Algorithm FirstAlgorithm where
    type CanFailWith FirstAlgorithm = Either Error1 Error2
    ...

instance Algorithm SecondAlgorithm where
    type CanFailWith SecondAlgorithm = Either Error1 (Either Error2 Error3)
    ...

这个选项对用户不是很友好,因为很难使用它的分支结构,例如

代码语言:javascript
复制
 testError (Left Error1)          = ...
 testError (Right (Left Error2))  = ...
 testError (Right (Right Error3)) = ...

有三个错误看起来没那么糟糕,但每多出一个错误都是值得的。

错误可能是简单的sum类型:

代码语言:javascript
复制
 data Error = Error1
            | Error2
            | Error3

但在这种情况下,我强制用户覆盖第一个算法中不可能的情况,这不会在Error3中失败

一个问题是:对于扩展错误,是否有任何通用且理想的简单的最终用户解决方案?

EN

回答 1

Stack Overflow用户

发布于 2013-07-10 14:11:48

你可以尝试这样的方法,每个算法都有自己的误差和类型。

代码语言:javascript
复制
{-# LANGUAGE TypeFamilies #-}

class Algorithm a where
    data CanFailWith a :: *
    check :: a -> [Int] -> Maybe (CanFailWith a)

data FirstAlgo = FirstAlgo deriving (Show)

instance Algorithm FirstAlgo where
    data CanFailWith FirstAlgo = FError1 |  FError2
    check a x = Nothing

data SecondAlgo = SecondAlgo deriving (Show)

instance Algorithm SecondAlgo where
    data CanFailWith SecondAlgo = SError1 | SError2 | SError3
    check a x = Nothing


testError :: CanFailWith SecondAlgo -> ()
testError SError1 = ()
testError SError2 = ()
testError SError3 = ()
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17562486

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档