Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Consider adding a safe version of toEnum for Bounded types. #286

Open
lierdakil opened this issue Apr 30, 2023 · 0 comments
Open

Consider adding a safe version of toEnum for Bounded types. #286

lierdakil opened this issue Apr 30, 2023 · 0 comments

Comments

@lierdakil
Copy link
Contributor

toEnum is partial. If the type is not only Enum but also Bounded it's simple enough to implement a non-partial version, e.g.

toEnumSafe :: forall a. (Enum a, Bounded a) => Int -> Maybe a
toEnumSafe i = guard (inBounds i) $> toEnum i where
  inBounds = inRange $ join bimap (fromEnum @a) (minBound, maxBound)
{-# INLINE toEnumSafe #-} -- the hope is most of 'inBounds' can be evalueated at compile time if 'a' is known

(inRange is defined in Data.Ix)

There are versions of this in relude and safe. It's occasionally very useful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant