Saturday, 30 April 2016

Haskell: Numeric types

Following are the basic numeric types supported by Haskell. All these numeric types are instances of Num.

Type
Description
Int
It is bounded integer type, represent integer values, For 32-bit machines the range goes from -2147483648 to 2147483647. For 64-bit machine the range goes from -9223372036854775808 to 9223372036854775807
Integer
It is unbounded integer type, represent arbitrarily large integer values. Size is limited by the amount of memory available on your machine.
Float
Single precision floating point value. Used to represent real numbers like 10.32, 9.86 etc., Usage of Float is discouraged, since Haskell compilers are written Double data type efficient code.
Double
Double precision floating point value. Used to represent real numbers like 10.32, 9.86 etc.,

Following code snippet gives you the maximum and minimum values of Int type.


variable.hs
biggestInt, smallestInt :: Int
biggestInt  = maxBound
smallestInt = minBound

Prelude> :load variable.hs
[1 of 1] Compiling Main             ( variable.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> biggestInt
9223372036854775807
*Main> 
*Main> smallestInt
-9223372036854775808

When a function signature supports a type T, then it can able to support all the child types of type T.


For example,
Prelude> :t (+)
(+) :: Num a => a -> a -> a


Operator + takes any variable of type Num, so it can support all sub types like Int, Integer, Float, Double.
Prelude> 10 + 90.09
100.09
Prelude> 10.01+100.98
110.99000000000001
Prelude> 10.01+987
997.01





Previous                                                 Next                                                 Home

No comments:

Post a Comment