Skip to content

Instantly share code, notes, and snippets.

@DanBurton
Created February 27, 2019 04:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DanBurton/45573f9ca85748c265cf229a6ed120c5 to your computer and use it in GitHub Desktop.
Save DanBurton/45573f9ca85748c265cf229a6ed120c5 to your computer and use it in GitHub Desktop.
Safe integral coercions via bounds checking
{-# LANGUAGE ScopedTypeVariables, TypeApplications #-}
import Data.Int (Int32, Int64)
fromIntegralMay :: forall b a. (Bounded b, Integral a, Integral b) => a -> Maybe b
fromIntegralMay a | a > fromIntegral (maxBound @b) || a < fromIntegral (minBound @b) = Nothing
fromIntegralMay a = Just (fromIntegral a)
justMin = fromIntegralMay @Int32 (-2147483648 :: Int64)
justMax = fromIntegralMay @Int32 (2147483647 :: Int64)
nothingMin = fromIntegralMay @Int32 (-2147483649 :: Int64)
nothingMax = fromIntegralMay @Int32 (2147483648 :: Int64)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment