Skip to content

Please provide instance for (Enum a, Bounded a) for Random #21

Description

@kvanbere

It would be really nice to be able to do something like this:

> data Action = Code | Eat | Sleep deriving (Bounded, Enum)
> randomR :: IO Action
Eat

The implementation for (Enum a, Bounded a) => can cheat a little to get a valid range (psuedo, for randomRIO since it's easier/shorter to show):

let lower = fromEnum (minBound :: a)
let upper = fromEnum (maxBound :: a)
return $ toEnum <$> randomRIO (lower, upper)

Note the usage of the underlying instance for Int to select a constructor.

It would have been magical if we could have just a Enum a => instance, but I can't think of a way to do it.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions