用几个单词描述一个问题。我想我有一个算法来检查一些东西,根据算法的不同,它可能会失败,并出现略有不同的错误,例如:
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)
...这个选项对用户不是很友好,因为很难使用它的分支结构,例如
testError (Left Error1) = ...
testError (Right (Left Error2)) = ...
testError (Right (Right Error3)) = ...有三个错误看起来没那么糟糕,但每多出一个错误都是值得的。
错误可能是简单的sum类型:
data Error = Error1
| Error2
| Error3但在这种情况下,我强制用户覆盖第一个算法中不可能的情况,这不会在Error3中失败
一个问题是:对于扩展错误,是否有任何通用且理想的简单的最终用户解决方案?
发布于 2013-07-10 14:11:48
你可以尝试这样的方法,每个算法都有自己的误差和类型。
{-# 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 = ()https://stackoverflow.com/questions/17562486
复制相似问题