Haskell如何添加可以处理List of Maybe的实例



我还没有找到任何此类情况的好例子。

我有这样的数据类型和一个带有实例的类:

data Type1 = Const1 | Const2
deriving Show
data Type2 = Type2 Int 
deriving Show

class Class a where
function :: a -> Int

instance Class Type1 where
function Const1 = 2
function Const2 = 3

instance Class Type2 where
function (Type2 x) = x * 2

应该添加可以这样计算的实例:

函数〔Just(Const2(,Nothing,Just(Const1(〕

函数[Anothing,Nothing,Just(Type2 1(,Just

有这样的方法吗?

instance Class (Maybe a) where
function Nothing = 0
function (Just x) = function x <--- gives an error

instance Class [a] where
function [] = 0
function [x] = function x <--- error
function (x:sx) = function x + function xs <--- error

只有当aClass类型类的成员时,这才有效,因此您需要将其添加为约束:

--           ↓ add a typeconstraint
instanceClass a =>Class (Maybe a) where
function Nothing = 0
function (Just x) = function x
--           ↓ add a typeconstraint
instanceClass a =>Class [a] where
function [] = 0
function [x] = function x
function (x:xs) = function x + function xs

事实上,您编写了例如function (Just x) = function x,但只有当function x有意义时才有效,而a(由Maybe包装的类型(就是Class类型类的实例。

然后我们可以确定样本列表的function

Prelude> function [Just (Const2), Nothing, Just (Const1)]
5
Prelude> function [Nothing, Nothing, Just (Type2 1), Just (Type2 2)]
6

您需要这样说:

instance Class a => Class (Maybe a) where ....

同样

instance Class a => Class [a] where ...

这意味着,如果a是,则Maybe a只是一个实例,对于[a]也是如此。这反过来又允许您在实现中使用function a

相关内容

最新更新