问题描述
我想创建一个有限的特定范围的新整数类型。我试过:
$ 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.
这篇关于如何创建一定范围内的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!