首页 > 解决方案 > Haskell如何添加可以处理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)]

函数 [Nothing, Nothing, Just (Type2 1), Just (Type2 2)]

有没有办法做到这一点?

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

标签: haskell

解决方案


这仅适用于类型类a的成员Class,因此您需要将其添加为约束:

--           ↓ add a typeconstraint
instance Class a => Class (Maybe a) where
    function Nothing = 0
    function (Just x) = function x

--           ↓ add a typeconstraint
instance Class a => Class [a] where
    function [] = 0
    function [x] = function x
    function (x:xs) = function x + function xs

确实,您编写了 example 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

推荐阅读