Published online by Cambridge University Press: 05 November 2014
Numbers in Haskell are complicated because in the Haskell world there are many different kinds of number, including:
Int limited-precision integers in at least the range [−229, 229). Integer overflow is not detected.
Integer arbitrary-precision integers
Rational arbitrary-precision rational numbers
Float single-precision floating-point numbers
Double double-precision floating-point numbers
Complex complex numbers (defined in Data.Complex)
Most programs make use of numbers in one way or another, so we have to get at least a working idea of what Haskell offers us and how to convert between the different kinds. That is what the present chapter is about.
The type class Num
In Haskell all numbers are instances of the type class Num:
class (Eq a, Show a) ⇒ Num a where
(+),(−),(*) :: a → a → a
negate :: a → a
abs, signum :: a → a
fromInteger :: Integer → a
The class Num is a subclass of both Eq and Show. That means every number can be printed and any two numbers can be compared for equality. Any number can be added to, subtracted from or multiplied by another number. Any number can be negated. Haskell allows -x to denote negate x; this is the only prefix operator in Haskell.
The functions abs and signum return the absolute value of a number and its sign.
To save this book to your Kindle, first ensure [email protected] is added to your Approved Personal Document E-mail List under your Personal Document Settings on the Manage Your Content and Devices page of your Amazon account. Then enter the ‘name’ part of your Kindle email address below. Find out more about saving to your Kindle.
Note you can select to save to either the @free.kindle.com or @kindle.com variations. ‘@free.kindle.com’ emails are free but can only be saved to your device when it is connected to wi-fi. ‘@kindle.com’ emails can be delivered even when you are not connected to wi-fi, but note that service fees apply.
Find out more about the Kindle Personal Document Service.
To save content items to your account, please confirm that you agree to abide by our usage policies. If this is the first time you use this feature, you will be asked to authorise Cambridge Core to connect with your account. Find out more about saving content to Dropbox.
To save content items to your account, please confirm that you agree to abide by our usage policies. If this is the first time you use this feature, you will be asked to authorise Cambridge Core to connect with your account. Find out more about saving content to Google Drive.