Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
917 views
in Technique[技术] by (71.8m points)

haskell - How to create a type bounded within a certain range

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...