Haskell Type Signatures
A type signature is a line that states the type of a name before its definition. It sits directly above the definition it describes.
A signature sits above its definition
The signature line comes first. The definition follows on the next line.
double :: Int -> Int
double x = x * 2
main :: IO ()
main = print (double 21)Two inputs appear before the result
The signature for add lists two Int inputs. The Int after the last arrow is the result.
add :: Int -> Int -> Int
add x y = x + y
main :: IO ()
main = print (add 17 25)List and tuple types appear in signatures
A list type wraps its item type in brackets. A tuple type lists each part type in order.
sumOf :: [Int] -> Int
sumOf xs = sum xs
firstScore :: (String, Int) -> Int
firstScore (_, score) = score
main :: IO ()
main = print (sumOf [10, 20, 12], firstScore ("Ana", 95))Example
itemName :: (String, Int) -> String
itemName (name, _) = name
totalCost :: Int -> Int -> Int
totalCost count price = count * price
batchSize :: [Int] -> Int
batchSize xs = length xs
main :: IO ()
main = print (itemName ("pen", 8), totalCost 6 7, batchSize [4, 9, 2])Key points
- Signature form: a signature is the name, then ::, then the type.
- Reading ::: the symbol :: reads as "has type".
- Function type: Int -> Int describes a function that takes an Int and returns an Int.
- Arrow chain: in Int -> Int -> Int, the last type is the result and each earlier type is one input.
- List type: [Int] is the type of a list whose items are Int values.
- Tuple type: (String, Int) is the type of a pair holding a String and an Int.
In this example, itemName takes a (String, Int) pair and returns its String part. totalCost takes two Int inputs and multiplies them, giving 42. batchSize takes a list of Int values and returns its length, which is 3. The main line prints all three results as one tuple.
Note
a signature is a promise the compiler checks against the definition below it.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Haskell Playground
Exercise
What does the signature add :: Int -> Int -> Int describe?