如何创建限定在一定范围内的类型 [英] How to create a type bounded within a certain range

查看:24
本文介绍了如何创建限定在一定范围内的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个新的整数类型,它有一定的范围.我试过了:

I would like to create a new integral type which is bounded to a certain range. I have tried:

data PitchClass = PC Int deriving (Ord, Eq, Show)

instance Bounded PitchClass where
  minBound = PC 0
  maxBound = PC 11

然而,我想要的是如果像这样的东西就会失败

However, what I want is something that will fail if something like

PC 12

PC (-1)

正在尝试.

对于您希望对创建新类型设置约束的情况,是一种通用方法,在这种情况下,值构造函数不从模块中导出,而是导出返回类型实例并执行约束检查的函数?

Is the general approach for a situation in which you wish to place constraints on creating new types one in which the value constructors are not exported from the module, but rather functions which return instances of the type and which perform constraint checks are exported?

推荐答案

是的,不从模块中导出数据构造函数是可行的方法.

Yes, not exporting the data constructor from the module is the way to go.

相反,您导出一个函数,该函数执行您所说的检查.这通常称为智能构造函数.

Instead, you export a function which does the checking as you said. This is often called a smart constructor.

这篇关于如何创建限定在一定范围内的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆