4. Types

Created Friday 22 August 2014

Overview

Type Systems



Haskell's Type System

Exploring Types in GHCi

Explicit Type

str :: [Char]
str = "hello"

Explicit Function Type

foo :: Int -> Int
foo x = 2 * x + 1
add3Int :: Int -> Int -> Int -> Int
add3Int x y z = x + y + z

Type Annotation

x = 3 :: Int
y = (3 :: Int) + (2.1 :: Double) --ERROR
y' = 3 + 2.1 --NO ERROR

Type Inference

square x = x * x
nonsense = square "hello" --COMPILE TIME ERROR
brokenShowSquare x = "The square is: " ++ square x --COMPILE TIME ERROR

When to use Explicit Types

whats_wrong = x + y
where x = length "hello"
y = 6/2
whats_wrong' = x + y
where x :: Int
x = length "hello"
y :: Int
y = 6/2 --The division operator isn't defined for ints in Haskell

Polymorphic Functions

length_ints :: [Int] -> Int
length_ints [] = 0
length_ints (x:xs) = length_ints xs + 1

length_chars :: [Char] -> Int
length_chars [] = 0
length_chars (x:xs) = length_chars xs + 1
Enough just:
length [] = 0
length (x:xs) = length xs + 1
Or, explicitly
length :: [a] -> Int --'a' states here for 'any type' (not mandatory to be 'a')
length [] = 0
length (x:xs) = length xs + 1

Type Class Constraints

sum :: Num a => [a] -> a --'Num a =>' is a constraint on 'a'
sum [] = 0
sum (x : xs) = x + sum xs

show :: Show a => a -> [Char]

showSum :: (Num a, Show a) => [a] -> [Char]
showSum xs = show (sum xs)



Backlinks: