Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 8 other subscribers.

Data types

Haskell uses static typing. This means that the data type of any assignment or expression evaluation is determined at compile time before the program is run, (some languages don’t decide this until the program is running.) This generally means that the code you produce is less prone to errors as any clashing types in expressions will be caught before the program runs. It is worth considering that functions we write and their associated parameters should also be given a specified type.

Data typing is strong, so once a data type is set it can’t be changed. Also, Haskell automatically infers data types so you don’t need to, (but in some cases might want to,) declare data types to use. As you can imagine, Haskell uses the same types as most other languages. We can use the t: command to see what data type is inferred by different expressions:

Prelude>  :t 5
5 :: Num a => a
Prelude>  :t 1.23
1.23 :: Fractional a => a
Prelude>  :t 'a'
'a' :: Char
Prelude>  :t "Hello"
"Hello" :: [Char]
Prelude>  :t True
True :: Bool
Prelude>  :t (1, "tuple")
(1, "tuple") :: Num t => (t, [Char])

Notice that the behaviour of numerical values is perhaps unfamiliar. When we would expect to see int for the first line we get Num. Numbers are represented using type classes which are functions that are implemented differently depending on the type of data they receive. All numerical values and operators are part of the Num class (with subclasses below this). Ultimately numbers can end up as either:

  • Int: whole number (up to a maximum depending on if you are using a 32 or 64 bit computer)
  • Integer: an unbounded whole number
  • Float: single precision floating point
  • Double: double precision floating point

It’s probably not worth getting too hung up on these types and classes. Haskell will decide the best type for you if you don’t specify one.

On a side note you may have seen this behaviour before:

Prelude> 10/2
5.0

This is caused by the use of type classes. The division operator is actually part of the fractional class (a subclass itself) so operands used here have to become floats. This is why the result is not expressed as an integer.


Leave a comment

Your email address will not be published. Required fields are marked *