Function Types
You'll learn: How to represent functions as types by specifying what they take in and what they give back.
What is a Function Type?
In type systems, functions themselves have types! A function type describes the transformation a function performs by specifying two things:
- Domain – the type(s) of input parameters
- Codomain – the type of the return value
We write this as A → B, read as "A to B" or "A arrow B." This means: a function that accepts something of type A and returns something of type B.
Why Function Types Matter
Think of a function type as a contract. If you see Int → String, you immediately know:
- Give me an integer
- I'll give you back a string
This is different from just naming a function. The type tells you the shape of the transformation, not the behavior. Two functions toString and formatNumber might both have type Int → String, even though they do different things internally.
Multiple Parameters
For functions with multiple parameters, we can write:
(Int, String) → Bool– takes an integer and string pair (a product type), returns a boolean- Or in curried form:
Int → (String → Bool)– takes an integer, returns a function from string to boolean
Function Types Enable Higher-Order Functions
Once functions have types, we can pass them as arguments or return them as values. A function that accepts another function might have type:
(Int → Bool) → [Int] → [Int]– takes a predicate function and a list, returns a filtered list
Key Takeaway: Function types describe the input-output contract using the arrow notation A → B, enabling type checkers to verify that functions are used correctly and making higher-order programming type-safe.