Skip to content

Instantly share code, notes, and snippets.

@monadplus
Last active January 8, 2024 21:39
Show Gist options
  • Save monadplus/fbc6f808290beb133ba6827e25ecacd9 to your computer and use it in GitHub Desktop.
Save monadplus/fbc6f808290beb133ba6827e25ecacd9 to your computer and use it in GitHub Desktop.
Numbers in Haskell

Numbers in Haskell

Primitives types: Int, Integer, Float, and Double.

Derived: Complex, Rational, Scientific

Class structure

Class Operations Description Values
Num a (+), (-), (*), negate, abs - Int, Integer, Float, Double
(Num a, Ord a) => Real a - - -
(Real a, Enum a) => Integral a div, rem, quot whole-number divison Int, Integer
Num a => Fractional a (/) division -
Fractional a => Floating a - trigonometric, logarithmic, exponential Float, Double
(Real a, Fractional a) => RealFrac a truncate, round, ceiling, floor - Float, Double

Conversions

Integer to Float:

fromIntegral :: (Num b, Integral a) => a -> b

coord2ToCoord1 :: (Float, Float) -> (Int, Int)
coord2ToCoord1 (x, y) = (round (500 * x), round (500 - 500 * y))

Float to Integer;

ceiling  :: (RealFrac a, Integral b) => a -> b
floor    :: (RealFrac a, Integral b) => a -> b
truncate :: (RealFrac a, Integral b) => a -> b
round    :: (RealFrac a, Integral b) => a -> b

coord1ToCoord2 :: (Int, Int) -> (Float, Float)
coord1ToCoord2 (x, y) = (fromIntegral x/500, (500 - fromIntegral y)/500)

Special cases:

fromInteger :: Num a => Integer -> a
toInteger:: Integral a => a -> Integer

Coercions

Careful dangerous functions

fromInteger             :: (Num a) => Integer -> a
fromRational            :: (Fractional a) => Rational -> a
toInteger               :: (Integral a) => a -> Integer
toRational              :: (RealFrac a) => a -> Rational
fromIntegral            :: (Integral a, Num b) => a -> b
fromRealFrac            :: (RealFrac a, Fractional b) => a -> b

fromIntegral            =  fromInteger . toInteger
fromRealFrac            =  fromRational . toRational

Defaults

You can annotate modules with the default pragma. If there's an ambiguous standard numeric type variable, the compiler will try to disambiguate it by applying the first concret type that satisfies the type variable constraints.

default (Integer, Double) -- default one

default (Integer, Rational, Double) -- alternative
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment