Skip to content
LumenaryAcademy
Foundations 50 min

Expressions, types and type inference

Everything is an expression, every expression has a type, and the compiler works most of them out for you.

Code tested · 3AI-draftedAwaiting review by a computer scientist
MotivationH

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 = 5 says that x means 5, everywhere in its scope, forever. There is no assignment and no x = 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.
DefinitionsH

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.

TypeValuesNotes
Intwhole numbers from about −9.2 × 10¹⁸ to 9.2 × 10¹⁸Fixed size, fast. Overflow wraps around silently.
Integerevery whole numberArbitrary precision; never overflows. Slower than Int.
Double64-bit floating-point numbersFloat is the 32-bit version, rarely used.
Charone Unicode character: 'a', 'λ', '\n'Single quotes.
Stringtext: "Accra"Double quotes. A String is a list of Char, written [Char].
BoolTrue, FalseOperators &&, ||, 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 -> Boolfunctions from Int to BoolThe 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".

Worked examplesH

Values, operators and conversions

Numbers

haskell
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))
text
18446744073709551616
0
9223372036854775807
(3,1)
(-4,1)
(-3,-1)
3.5
0.30000000000000004
2.5
(2,4,-2,-3)

Line by line:

  • 2 ^ 64 :: Integer is exact. The same expression at type Int wraps around to 0, without any error. Use Int for counts and indexes, where the range is ample, and Integer when 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 :: Int asks for the largest Int.
  • Writing a function name between backticks makes it an infix operator: 7 `div` 2 is div 7 2. Integer division comes in two pairs. div and mod round towards negative infinity, so mod has the sign of the divisor; quot and rem round towards zero, like C and Java. For non-negative numbers they agree. Note the parentheses in (-7): a bare -7 next to a function would be read as subtraction.
  • / is division for fractional types only. 7 / 2 is 3.5 because the literals become Doubles.
  • 0.1 + 0.2 shows the usual floating-point rounding, exactly as in every language that uses IEEE 754 doubles.
  • length returns an Int, and Haskell never converts numbers implicitly: length "Kyoto" / 2 is a type error. fromIntegral converts any integral number to any numeric type, here a Double.
  • round rounds halves to the even neighbour (2.5 becomes 2, 3.5 becomes 4), which avoids a bias when you round many values. truncate cuts towards zero, floor goes down.

Text and other values

haskell
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")
text
Montevideo has 1319108 people.
(10,"Monte")
('\955',"na\239ve",[True,False],(3,'x',"three"))
["the","quick","brown","fox"]
43
("3.0","\"hi\"")
  • Inside a do block, let introduces local names. Several names can share one let if they are indented to the same column.
  • A tuple prints as its parts in parentheses. take 5 city works because a string is a list of characters.
  • The third line is worth a second look. print uses show, and show is meant to produce Haskell source code for a value, safely printable anywhere. For characters outside plain ASCII it uses escape codes: '\955' is λ, and \239 is ï. When you want to display text to a person, use putStrLn on the string itself; keep show and print for debugging and for numbers.
  • words splits on any run of spaces. read is the opposite of show: it parses a string into a value of the type you ask for. If the string is not valid, read crashes the program; lesson 7 shows readMaybe, the safe version.
  • The last line confirms that show writes source code: show 3.0 is the three characters 3.0, while show "hi" is a string that contains the quotation marks, which print then shows again with escapes.

Local names, if, and where

haskell
-- 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)
text
15.5
19.38
9.32
long trip, short trip

Two ways to name things locally appear here.

  • let ... in expr is an expression: the names after let are visible in expr after in. (Inside do you leave out the in; the names are visible in the rest of the block.)
  • where attaches definitions to a whole equation, after the fact. Many Haskell programmers prefer where for 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.

IntuitionH

How type inference works

Ask GHCi for the types of a few definitions that have no signatures. These are its exact answers:

text
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) :: Int

How did GHC know? It treats the program as a set of equations about types and solves them, a little like a puzzle.

  • In greet, name is used as an argument of ++, whose other argument is the string "Hello, ". Both sides of ++ must have the same type, so name :: [Char], and the result is [Char] too.
  • In swap, nothing constrains a or b at all: they can be anything. So GHC gives the most general type, with type variables. (It happened to name them b and a; the names don't matter.)
  • In double, x is multiplied, and * belongs to the class Num. So x can be any type in Num, and the result has that same type.
  • In isAdult, age is compared with >= (class Ord, for ordered types) and with the literal 18 (class Num). 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 misconceptionsH

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

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-upComputational

What does this program print?

main :: IO ()
main = print ((-17) `mod` 5)

2. Expressions, types and type inference

CoreComputational

What does this program print?

main :: IO ()
main = print (round 4.5, round 5.5, truncate (-4.5))

3. Expressions, types and type inference

CoreHuman

Which type does GHC infer for f x y = x ++ y ++ x?

Choose one

4. Expressions, types and type inference

CoreComputational

This definition does not compile:

averageWordLength :: [String] -> Double
averageWordLength ws = sum (map length ws) / length ws

Which version does?

Choose one

5. Expressions, types and type inference

CoreComputational

What 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

CoreHuman

What happens when a program evaluates (maxBound :: Int) + 1?

Choose one

7. Expressions, types and type inference

StretchComputational

What 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