How to create a type bounded within a certain range

前端 未结 2 1366
没有蜡笔的小新
没有蜡笔的小新 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).

提交回复
热议问题