How to create a type bounded within a certain range

前端 未结 2 1352
没有蜡笔的小新
没有蜡笔的小新 2020-12-06 09:30

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 Bou         


        
相关标签:
2条回答
  • 2020-12-06 10:28

    An alternate solution for cases where the number of total values is this small is to simply enumerate the possible constructors.

    data PitchClass = A | Bb | B | C | Db | D | Eb | E | F | Gb | G | Ab
        deriving (Eq, Ord, Bounded, Show, Read)
    

    There are half a dozen different hacks you can try from here to make it more convenient in various ways; for example, you can derive Enum to get toEnum . fromEnum = id (and toEnum (-1) = {- an exception -}), or you can write a custom Integral instance to get 0 = A (and your choice of behavior for -1).

    0 讨论(0)
  • 2020-12-06 10:31

    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.

    0 讨论(0)
提交回复
热议问题