3 - Numbers
Published online by Cambridge University Press: 05 November 2014
Summary
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.
- Type
- Chapter
- Information
- Thinking Functionally with Haskell , pp. 49 - 62Publisher: Cambridge University PressPrint publication year: 2014