Everything is an expression
In Python or Java, a program is built from two kinds of thing. Statements do something: an assignment, a for loop, a return. Expressions compute a value: x + 1, len(names). Haskell has, essentially, only expressions. A function body is one expression. An if is an expression with a value, so it must always have an else (otherwise what would its value be when the condition is false?). Even a do block, which looks like a list of statements, is an expression whose value is an action.
And every expression has a type, known before the program runs. You have already met a few: Double, String, IO (). This lesson covers the everyday types, how you write them, and how GHC infers them when you don't. Two habits of mind will help from the start.
- A name is a definition, not a box.
x = 5says thatxmeans 5, everywhere in its scope, forever. There is no assignment and nox = x + 1. When you need a new value, you give it a new name. - Types are a conversation with the compiler. Write the type you intend, and GHC checks that your code agrees. When it disagrees, the error tells you exactly where your idea and your code parted ways.
The everyday types
Definition— Type and type signature
A type is a set of values together with what you may do with them. A type signature name :: Type declares the type of a name. Type names start with a capital letter; ordinary names start with a lower-case letter.
| Type | Values | Notes |
|---|---|---|
Int | whole numbers from about −9.2 × 10¹⁸ to 9.2 × 10¹⁸ | Fixed size, fast. Overflow wraps around silently. |
Integer | every whole number | Arbitrary precision; never overflows. Slower than Int. |
Double | 64-bit floating-point numbers | Float is the 32-bit version, rarely used. |
Char | one Unicode character: 'a', 'λ', '\n' | Single quotes. |
String | text: "Accra" | Double quotes. A String is a list of Char, written [Char]. |
Bool | True, False | Operators &&, ||, not. |
() | () | "Unit": the type with one value, for "nothing interesting". |
(Int, String) | pairs like (3, "three") | Tuples of any fixed size, with parts of different types. |
[Int] | lists like [1, 2, 3] | Any length, but every element has the same type. |
Int -> Bool | functions from Int to Bool | The arrow is part of the type. |
Comparison operators are ==, /= (not equal; Haskell does not use !=), <, <=, >, >=.
Definition— Type variable and polymorphism
A lower-case name inside a type, such as the a in [a] -> Int, is a type variable: it stands for any type. A function whose type contains type variables is polymorphic: length :: [a] -> Int counts the elements of a list of anything.
Definition— Class constraint
A constraint such as Num a => at the front of a type restricts a type variable to types that belong to a type class. double :: Num a => a -> a works for any numeric type a: Int, Integer, Double and so on, but not String. Lesson 6 covers type classes properly; for now read C a => as "for any type a that supports the operations of C".
Values, operators and conversions
Numbers
main :: IO ()
main = do
let big = 2 ^ 64 :: Integer
wrapped = 2 ^ 64 :: Int
print big
print wrapped
print (maxBound :: Int)
print (7 `div` 2, 7 `mod` 2)
print ((-7) `div` 2, (-7) `mod` 2)
print ((-7) `quot` 2, (-7) `rem` 2)
print (7 / 2)
print (0.1 + 0.2 :: Double)
print (fromIntegral (length "Kyoto") / 2)
print (round 2.5, round 3.5, truncate (-2.7 :: Double), floor (-2.7 :: Double))18446744073709551616
0
9223372036854775807
(3,1)
(-4,1)
(-3,-1)
3.5
0.30000000000000004
2.5
(2,4,-2,-3)Line by line:
2 ^ 64 :: Integeris exact. The same expression at typeIntwraps around to 0, without any error. UseIntfor counts and indexes, where the range is ample, andIntegerwhen numbers may grow without bound.::inside an expression is a type annotation: it tells GHC which type you mean for an expression that could have several.maxBound :: Intasks for the largestInt.- Writing a function name between backticks makes it an infix operator:
7 `div` 2isdiv 7 2. Integer division comes in two pairs.divandmodround towards negative infinity, somodhas the sign of the divisor;quotandremround towards zero, like C and Java. For non-negative numbers they agree. Note the parentheses in(-7): a bare-7next to a function would be read as subtraction. /is division for fractional types only.7 / 2is3.5because the literals becomeDoubles.0.1 + 0.2shows the usual floating-point rounding, exactly as in every language that uses IEEE 754 doubles.lengthreturns anInt, and Haskell never converts numbers implicitly:length "Kyoto" / 2is a type error.fromIntegralconverts any integral number to any numeric type, here aDouble.roundrounds halves to the even neighbour (2.5 becomes 2, 3.5 becomes 4), which avoids a bias when you round many values.truncatecuts towards zero,floorgoes down.
Text and other values
main :: IO ()
main = do
let city = "Montevideo"
population = 1319108 :: Int
line = city ++ " has " ++ show population ++ " people."
putStrLn line
print (length city, take 5 city)
print ('λ', "naïve", [True, False], (3 :: Int, 'x', "three"))
print (words " the quick brown fox ")
print (read "42" + 1 :: Int)
print (show 3.0, show "hi")Montevideo has 1319108 people.
(10,"Monte")
('\955',"na\239ve",[True,False],(3,'x',"three"))
["the","quick","brown","fox"]
43
("3.0","\"hi\"")- Inside a
doblock,letintroduces local names. Several names can share oneletif they are indented to the same column. - A tuple prints as its parts in parentheses.
take 5 cityworks because a string is a list of characters. - The third line is worth a second look.
printusesshow, andshowis meant to produce Haskell source code for a value, safely printable anywhere. For characters outside plain ASCII it uses escape codes:'\955'is λ, and\239is ï. When you want to display text to a person, useputStrLnon the string itself; keepshowandprintfor debugging and for numbers. wordssplits on any run of spaces.readis the opposite ofshow: it parses a string into a value of the type you ask for. If the string is not valid,readcrashes the program; lesson 7 showsreadMaybe, the safe version.- The last line confirms that
showwrites source code:show 3.0is the three characters3.0, whileshow "hi"is a string that contains the quotation marks, whichprintthen shows again with escapes.
Local names, if, and where
-- A taxi fare: a fixed starting charge plus a rate per kilometre,
-- with a 25% surcharge at night, rounded to two decimal places.
fare :: Bool -> Double -> Double
fare night km =
let base = 3.5 + 1.2 * km
surcharge = if night then base * 0.25 else 0
in roundTo 2 (base + surcharge)
where
roundTo :: Int -> Double -> Double
roundTo digits x = fromIntegral (round (x * 10 ^ digits) :: Integer) / 10 ^ digits
tripKind :: Double -> String
tripKind km = if km > 20 then "long trip" else "short trip"
main :: IO ()
main = do
print (fare False 10)
print (fare True 10)
print (fare True 3.3)
putStrLn (tripKind 25 ++ ", " ++ tripKind 4.5)15.5
19.38
9.32
long trip, short tripTwo ways to name things locally appear here.
let ... in expris an expression: the names afterletare visible inexprafterin. (Insidedoyou leave out thein; the names are visible in the rest of the block.)whereattaches definitions to a whole equation, after the fact. Many Haskell programmers preferwherefor helper functions, because the main formula comes first and the details follow, the way a textbook writes "where r is the radius".
if night then base * 0.25 else 0 is an ordinary expression with a value, which is why it can sit on the right of =. Both branches must have the same type.
Finally, indentation matters. The lines of a let, a where or a do block must start in the same column, and continuation lines must be indented further than the start of the definition. Most editors with the Haskell Language Server will indent correctly for you, and the formatters described in lesson 10 settle the remaining questions of style.
How type inference works
Ask GHCi for the types of a few definitions that have no signatures. These are its exact answers:
ghci> let greet name = "Hello, " ++ name
ghci> :t greet
greet :: [Char] -> [Char]
ghci> let swap (a, b) = (b, a)
ghci> :t swap
swap :: (b, a) -> (a, b)
ghci> let double x = x * 2
ghci> :t double
double :: Num a => a -> a
ghci> let isAdult age = age >= 18
ghci> :t isAdult
isAdult :: (Ord a, Num a) => a -> Bool
ghci> :t double (21 :: Int)
double (21 :: Int) :: IntHow did GHC know? It treats the program as a set of equations about types and solves them, a little like a puzzle.
- In
greet,nameis used as an argument of++, whose other argument is the string"Hello, ". Both sides of++must have the same type, soname :: [Char], and the result is[Char]too. - In
swap, nothing constrainsaorbat all: they can be anything. So GHC gives the most general type, with type variables. (It happened to name thembanda; the names don't matter.) - In
double,xis multiplied, and*belongs to the classNum. Soxcan be any type inNum, and the result has that same type. - In
isAdult,ageis compared with>=(classOrd, for ordered types) and with the literal18(classNum). Both constraints are collected.
This algorithm, worked out by Roger Hindley and Robin Milner and extended for type classes, finds the most general type whenever one exists, without you writing a single annotation. Haskell programmers still write signatures for every top-level definition. A signature documents intent, makes error messages point at the right place, and sometimes deliberately chooses a less general type: fare above says Double, although its formula would work for any fractional type.
Note
When a numeric type is still undecided at the end, as in print (2 ^ 100), GHC uses a default: Integer for whole-number expressions and Double for fractional ones. That is why the examples print sensible results. With the warning flag -Wall turned on, GHC tells you when it defaults, and many teams add a signature or annotation at those places.
Common misconceptions
Misconception
"x = x + 1 increments x." In Haskell it defines x in terms of itself: to know x, compute x + 1, which needs x, and so on forever. A compiled program usually detects this and stops with the message <<loop>>; in GHCi or runghc it may simply hang until you press Ctrl-C. To get a new value, give it a new name, let x' = x + 1, or, much more often, pass it to the next call of a function.
Misconception
"Haskell will turn my Int into a Double when needed." It never converts implicitly, not even from Int to Integer. This feels fussy for a week and then saves you from a class of bugs other languages hide. The conversions you need are few: fromIntegral from any integral type to any numeric type; round, truncate, floor and ceiling from fractional to integral; show and read to and from text.
Misconception
"Int is safe because Haskell is a safe language." Type-safe, yes; overflow-safe, no. Int arithmetic wraps around without warning, for speed, exactly as in C or Java. When a value could become very large (a factorial, a sum of millions of amounts in the smallest currency unit), use Integer.
Misconception
"abs -3 means the absolute value of minus three." Haskell parses it as abs - 3, subtracting 3 from the function abs, and GHC answers with a puzzling error about a missing instance for a function type. Negative literals next to function applications need parentheses: abs (-3).
Exercises
Use GHCi's :t to check your reasoning about types, and run the programs to check your predictions.
1. Expressions, types and type inference
Warm-upComputationalWhat does this program print?
main :: IO ()
main = print ((-17) `mod` 5)
2. Expressions, types and type inference
CoreComputationalWhat does this program print?
main :: IO ()
main = print (round 4.5, round 5.5, truncate (-4.5))
3. Expressions, types and type inference
CoreHumanWhich type does GHC infer for f x y = x ++ y ++ x?
4. Expressions, types and type inference
CoreComputationalThis definition does not compile:
averageWordLength :: [String] -> Double
averageWordLength ws = sum (map length ws) / length ws
Which version does?
5. Expressions, types and type inference
CoreComputationalWhat does this program print?
score :: Int -> Int
score n =
let bonus = if n > 10 then 5 else 0
in base + bonus
where
base = n * 2
main :: IO ()
main = print (score 12 + score 3)
6. Expressions, types and type inference
CoreHumanWhat happens when a program evaluates (maxBound :: Int) + 1?
7. Expressions, types and type inference
StretchComputationalWhat does this program print? Write the two lines separated by a single space.
main :: IO ()
main = do
let w = "Lagos"
putStrLn (w ++ show (length w))
print (w ++ "!")
Further reading and resources
- Haskell 2010 Language Report, chapter 3: ExpressionsThe precise definition of every kind of expression.
- Haskell 2010 Language Report, chapter 6: Predefined Types and ClassesThe standard numeric types and how they relate.
- The base package on HackageDocumentation for the Prelude and every standard module, with links to the source.
- HoogleType a name such as fromIntegral, or a type such as Int -> Double, and find the function.