A different way to write programs
In most languages you have met, a program is a list of instructions. Set this variable, loop over that list, change this field, print that line. The computer follows the steps in order, and the meaning of the program is the effect those steps have on memory and on the outside world.
Haskell starts from another idea. A Haskell program is mostly a collection of definitions: this name means that expression, this function turns an input into that output. Running the program means working out the value of an expression, much as you work out the value of 3 × (4 + 5) on paper. You never say "now change x"; you say what x is.
Three design decisions follow from that idea, and together they explain almost everything that feels unusual about the language.
- Purity. A Haskell function, given the same arguments, always returns the same result, and it does nothing else: it does not print, change a global variable or read a file behind your back. Effects still happen, of course, or programs would be useless, but they are described by values of a special type,
IO, and the type of every function tells you whether it may perform them. - Laziness. Haskell evaluates an expression only when its value is actually needed. You can define the infinite list of all prime numbers and take the first ten; the other primes are never computed.
- Static types with inference. Every expression has a type, checked before the program runs, but you rarely need to write types down: the compiler works them out. Experienced Haskell programmers still write a type signature above every top-level function, because the signature is the most useful one-line documentation a function can have.
Why would anyone want this? Because code that cannot change hidden state is much easier to reason about, test, reuse and run in parallel. When a function's type says Int -> Int, you know it cannot launch a missile or corrupt a database; it can only compute a number. Haskell programmers often say that once a program type-checks, it frequently just works. That is an exaggeration, but a useful one: the compiler catches a surprising share of the mistakes that other languages leave for testing or for users to find.
There are costs, and this course will be honest about them. Laziness makes the time and memory a program uses harder to predict, and lesson 8 is devoted to taming it. The vocabulary (functor, monad, type class) sounds forbidding at first, and the learning curve is real. But the ideas are smaller than their names, and we will meet each one through concrete code before naming it.
Where Haskell came from
By the mid-1980s there were more than a dozen lazy functional languages, most of them research projects, each with its own syntax and few users. At the 1987 conference on Functional Programming Languages and Computer Architecture in Portland, Oregon, a group of researchers agreed that this fragmentation was holding the whole field back, and formed a committee to design one common language: open, freely implementable, suitable for teaching, research and real applications. They named it after Haskell Brooks Curry, an American logician whose work on combinatory logic underlies much of functional programming (the word currying, which you will meet in lesson 3, is also his).
The first Haskell Report appeared in 1990. The language then went through several revisions, the most important being Haskell 98, a stable standard meant for teaching and long-lived code, and Haskell 2010, the current official report. Along the way Haskell gave the wider programming world two ideas in particular. Type classes, proposed by Philip Wadler and Stephen Blott in 1989, let one function work on many types in a disciplined way; Rust's traits, Swift's protocols and Scala's implicits all owe them something. And monads, brought from category theory into programming by Eugenio Moggi and popularised by Wadler, gave a pure language a clean way to describe input and output; Haskell adopted monadic IO in version 1.3, in 1996.
One implementation came to dominate: the Glasgow Haskell Compiler (GHC), begun at the University of Glasgow around 1990 and developed for many years at Microsoft Research in Cambridge by Simon Peyton Jones, Simon Marlow and others, with a large community of contributors. Today almost everyone writes "Haskell" to mean "the language GHC accepts", which is Haskell 2010 plus many optional language extensions. Since GHC 9.2 (2021) the most widely used extensions are bundled into a language edition called GHC2021, which is what you get by default; a newer edition, GHC2024, can be switched on per project. The Haskell Foundation, founded in 2020, supports the infrastructure, the tooling and the community.
Haskell has never been among the most widely used languages, but it is used seriously: at banks and trading firms, in the Cardano blockchain, in tools many programmers use daily without knowing their language (the document converter Pandoc and the shell-script checker ShellCheck are both written in Haskell), in compilers, and in a great deal of programming-language research.
The toolchain
Definition— GHC
GHC is the Haskell compiler. It turns source files (ending in .hs) into native executables, applying aggressive optimisations when you pass -O or -O2. It also contains an interpreter, which the next two tools use.
Definition— GHCi and runghc
GHCi is GHC's interactive environment (a REPL: read, evaluate, print, loop). You type an expression and see its value; you load a file and try its functions one by one. runghc runs a source file directly through the interpreter, without producing an executable, which is handy for scripts and small experiments.
Definition— Cabal and Stack
Cabal is the standard build tool and package manager: a project has a .cabal file listing its source files and dependencies, and cabal build, cabal run and cabal test do the rest, downloading libraries from Hackage, the central package archive. Stack is an alternative build tool built on the same package format that pins every dependency to a tested, curated snapshot of package versions called Stackage. Teams use one or the other; lesson 10 compares them.
Definition— GHCup
GHCup is the official installer. It installs GHC, Cabal, Stack and the Haskell Language Server (HLS, which gives editors such as VS Code, Neovim and Emacs type information on hover, errors as you type and refactorings), and lets you keep several versions side by side and switch between them.
Follow the instructions on haskell.org/ghcup: on Linux and macOS it is a one-line shell command, on Windows a PowerShell command. The installer asks a few questions; the defaults are fine. Afterwards, check what you have:
ghc --version
cabal --version
ghcup list # what is installed and what is availableThe programs in this course were run with GHC 9.14. Any recent GHC will run them; if yours is older than 9.10, one detail differs (foldl' had to be imported from Data.List before then), and the lesson where it appears will say so. If you would rather not install anything yet, the Haskell Playground runs every program in this course in your browser.
Your first programs
Hello, world
Save this as hello.hs:
main :: IO ()
main = do
putStrLn "Hello, world!"
putStrLn "Sawubona, mhlaba! Bonjour, le monde! Merhaba, dünya!"Hello, world!
Sawubona, mhlaba! Bonjour, le monde! Merhaba, dünya!and run it with runghc hello.hs. Read it line by line.
main :: IO ()is a type signature. Read::as "has type".mainhas typeIO (): it is an IO action, a description of some input and output, that produces nothing interesting when it is done.(), pronounced "unit", is the type with exactly one value, also written(); it plays the rolevoidplays in C or Java.main = do ...definesmain. Every Haskell program starts by carrying out the action calledmain.doglues several IO actions into one, to be performed in order. The lines inside it must line up in the same column: Haskell uses indentation, as Python does, to see where a block starts and ends.putStrLntakes a string and gives back the action of printing it followed by a newline. Notice that there are no parentheses around the argument: in Haskell you apply a function by writing it next to its argument,putStrLn "hi", notputStrLn("hi").
Strings are Unicode, so the Zulu, French and Turkish greetings print as written.
Definitions, and a table
The next program defines a function of its own and uses it on a small list of cities.
-- Convert a temperature from degrees Celsius to degrees Fahrenheit.
toFahrenheit :: Double -> Double
toFahrenheit c = c * 9 / 5 + 32
report :: (String, Double) -> String
report (city, c) = city ++ ": " ++ show c ++ " C is " ++ show (toFahrenheit c) ++ " F"
main :: IO ()
main = mapM_ (putStrLn . report) [("Nairobi", 24), ("Oslo", -3), ("Lima", 19.5)]Nairobi: 24.0 C is 75.2 F
Oslo: -3.0 C is 26.6 F
Lima: 19.5 C is 67.1 FA lot is going on in a few lines, and every piece will get its own lesson, but you can already read it:
toFahrenheit :: Double -> Doublesays thattoFahrenheittakes aDouble(a floating-point number) and returns one. The definition below it is an equation:toFahrenheit cisc * 9 / 5 + 32.reporttakes a pair, written(city, c). Writing the pair's parts as names on the left of=is pattern matching: it takes the pair apart and names its two halves.++joins strings, andshowturns a value into a string.mapM_ f xsperforms the actionf xfor eachxin the listxs, in order. The function we give it,putStrLn . report, is two functions composed with.: firstreport, thenputStrLn.- Lines starting with
--are comments.
We never wrote a loop. Applying a function to every element of a list is so common that the standard library does it for you, and you will rarely write a loop by hand in Haskell.
Infinite lists, thanks to laziness
-- Every square number: 1, 4, 9, 16, ... The list never ends.
squares :: [Integer]
squares = [n * n | n <- [1 ..]]
main :: IO ()
main = do
print (take 6 squares)
print (takeWhile (< 200) squares)
print (sum (takeWhile (< 1000) squares))
print (2 ^ 100)[1,4,9,16,25,36]
[1,4,9,16,25,36,49,64,81,100,121,144,169,196]
10416
1267650600228229401496703205376[1 ..] is the list of all positive integers, and squares is the list of their squares, written as a list comprehension: "the list of n * n for every n drawn from [1 ..]". In most languages building this list would never finish. In Haskell nothing is computed until something asks for it: take 6 asks for six elements, so six squares are calculated, and takeWhile (< 200) keeps taking squares while they are less than 200 and then stops asking.
print is putStrLn . show: it shows any printable value. Lists print in square brackets. The last line shows that Integer, Haskell's default integer type for literals like these, has no upper limit: 2 ^ 100 is exact.
Running, compiling and exploring
Three ways to run a file
| Command | What happens | When to use it |
|---|---|---|
runghc hello.hs | Interprets the file and runs main. Nothing is left on disk. | Scripts, small experiments, the programs in these lessons. |
ghc -O2 hello.hs | Compiles to a native executable called hello (hello.exe on Windows), plus .hi and .o files GHC uses for separate compilation. Run it with ./hello. | When speed matters, or to ship a program. |
ghci hello.hs | Loads the file into the interactive environment so you can call its functions by hand. | Exploring, testing, learning. |
Compiled Haskell with -O2 is typically many times faster than interpreted code; real projects are always built with Cabal or Stack, which call GHC for you (lesson 10).
A session in GHCi
GHCi is where Haskell programmers spend a lot of their day. Start it with ghci, and you get a prompt. Here is a short session; the lines after each prompt are what GHCi printed.
ghci> 2 + 3 * 4
14
ghci> length "Ulaanbaatar"
11
ghci> :type map
map :: (a -> b) -> [a] -> [b]
ghci> :t 42
42 :: Num a => a
ghci> :quit
Leaving GHCi.Lines starting with a colon are GHCi commands, not Haskell. The ones you will use most:
| Command | Short | Meaning |
|---|---|---|
:type expr | :t | Show the type of an expression without evaluating it. |
:info name | :i | Show where a name is defined, and for a type, its definition and instances. |
:load file.hs | :l | Load a source file. |
:reload | :r | Reload after you edit the file. The edit, :r, try-again loop is the heart of working in GHCi. |
:quit | :q | Leave. |
The answer to :t 42 deserves a moment. GHCi did not say Int; it said Num a => a, "a value of any type a, provided a is a numeric type". A literal like 42 can be an Int, an Integer or a Double, depending on where it is used. That is your first glimpse of type classes, the subject of lesson 6.
Reading a type error
Suppose you try to join a number onto a string:
main :: IO ()
main = do
let age = 31 :: Int
putStrLn ("Age: " ++ age)GHC refuses to run the program and explains:
main.hs:4:24: error: [GHC-83865]
• Couldn't match expected type ‘[Char]’ with actual type ‘Int’
• In the second argument of ‘(++)’, namely ‘age’
In the first argument of ‘putStrLn’, namely ‘("Age: " ++ age)’
In a stmt of a 'do' block: putStrLn ("Age: " ++ age)
|
4 | putStrLn ("Age: " ++ age)
| ^^^Learn to read these from the top. main.hs:4:24 is the file, line and column. Expected type is what the context demands, here [Char] (a list of characters, which is what String means), because ++ joins two lists of the same type. Actual type is what you gave: an Int. The "In the ..." lines zoom out from the mistake to its surroundings, and the carets underline it. The fix is to convert the number with show age. The bracketed code GHC-83865 can be looked up on the Haskell Error Index for a longer explanation with examples.
Note
GHC's errors can be long, especially when type inference has travelled a long way from your mistake before noticing it. Two habits help: read the first error first, and add a type signature to every top-level function. Signatures stop inference at function boundaries, so the error appears where the mistake is, not three functions away.
Common misconceptions
Misconception
"A pure language cannot do input and output." It can and does: Haskell programs print, read files, talk to networks and databases. Purity means that effects are visible in the types. A function of type String -> Int cannot print; an action of type IO Int may perform effects and then produce an Int. You will see in lesson 7 that this separation is a tool, not a cage.
Misconception
"You need to learn category theory before you can write Haskell." You do not. Words like functor and monad come from mathematics, but in Haskell each one names a small, practical interface with a handful of functions. Many professional Haskell programmers have never studied category theory. This course introduces each idea through code you can run.
Misconception
"Lazy means slow." Laziness has a cost, the bookkeeping for values not yet computed, and it can cause memory problems you must learn to spot. But GHC's optimiser removes most of the overhead in compiled code, and laziness also saves work: nothing that is never needed is ever computed. Lesson 8 shows both sides.
Misconception
"Haskell is only an academic language." It began in research and is still a favourite there, but it also runs in production at companies in finance, blockchain, developer tools and web services. It is a smaller ecosystem than Python's or Java's, which is an honest trade-off when you choose it for a project.
Exercises
Try anything you are unsure of in GHCi or in the Haskell Playground.
1. First steps in Haskell
Warm-upHumanYou want to try a newer GHC release while keeping your current one installed, and switch between them. Which tool is made for that?
2. First steps in Haskell
Warm-upHumanA Haskell function has the type String -> Int. Which statement is true?
3. First steps in Haskell
CoreComputationalWhat does this program print? Write the lines separated by single spaces.
main :: IO ()
main = do
putStrLn ("Kia " ++ "ora")
print (3 + 4 * 2)
print "done"
4. First steps in Haskell
CoreComputationalWhat does this program print?
main :: IO ()
main = print (length (takeWhile (< 50) [n * n | n <- [1 ..]]))
5. First steps in Haskell
Warm-upHumanIn GHCi, which command (with its leading colon) shows the type of an expression without evaluating it? Give the short form or the long form.
6. First steps in Haskell
CoreHumanYou wrote a program that crunches a large data file and you want it to run as fast as possible. Which command should you use to build it?
7. First steps in Haskell
CoreComputationalGHC reports Couldn't match expected type ‘[Char]’ with actual type ‘Int’ and underlines count in putStrLn ("Total: " ++ count). What is the best fix?
Further reading and resources
- Get started with HaskellThe official instructions for installing the toolchain and running a first program.
- GHCupThe recommended installer for GHC, Cabal, Stack and the Haskell Language Server on Linux, macOS and Windows.
- GHC User's Guide: Using GHCiEvery GHCi command, from :type to the debugger.
- Haskell 2010 Language ReportThe current language standard.
- A History of Haskell: Being Lazy with Class · Paul Hudak, John Hughes, Simon Peyton Jones and Philip Wadler · 2007The designers' own account of how the language came about, written for the third History of Programming Languages conference (HOPL III).
- Haskell PlaygroundRun the programs of this lesson in the browser.