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

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

问题描述

我想创建一个有限的特定范围的新整数类型。我试过:
$ b $ pre $ data PitchClass = PC Int派生(Ord,Eq,Show)

实例有界PitchClass其中
minBound = PC 0
maxBound = PC 11

然而,我想要的是,如果像

  PC 12 

  PC(-1)

会被尝试。



您希望在创建新的类型时创建约束,其中值构造函数不是从模块中导出的,而是返回该类型的实例并执行约束检查的函数?


<解决方案是的,不从模块中导出数据构造函数是要走的路。



相反,你导出一个按照你说的去做检查的函数。这通常称为智能构造函数


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

or

PC (-1)

is attempted.

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天全站免登陆