haskell - 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
解决方案
这仅适用于类型类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
推荐阅读
- ios - 使用正则表达式或其他方法 Swift 在字符串中的模式中查找字符串模式
- scala - Play 应用的生产版本中的“未找到操作”
- javascript - 如何单击页面 JAVASCRIPT 中的特定文本
- c - 输入末尾的预期声明或语句(单链表)
- html - 使项目居中而不扩大页面的整体大小
- python - 仅使用数学库查找 n 因子的更快方法
- r - 将 cross(starts_with(), mean) 的结果分配给 R 数据框
- android - Markwon:列出子弹大小/样式?
- vb.net - 如何在 vb.net 中启动 .exe 文件并传入命令行参数
- cartopy - 如何确定任何 cartopy 投影的可见地图范围?