Search code examples
haskelltypestype-constructor

Haskell restricting integer values via enumeration


I want to do something like this:

data Bit = 0 | 1

But since the right hand side has to be a valid data constructor (?) I would have to use something like

data Bit = Zero | One

This isn't particularly good since I want to use the actual values 0 and 1. What's the best solution to my conundrum?


Solution

  • You might enjoy this cheeky Num instance I wrote some time ago:

    instance Num Bool where
        (+) = (/=)
        (*) = (&&)
        negate = id
        abs = id
        signum = id
        fromInteger = odd
    

    For example, in ghci:

    > (3 + 5) * 6 :: Bool
    False
    

    You should be able to use something similar, suitably modified to support your data Bit = O | I rather than data Bool = False | True.