What is Haskell and why it matters
| Pure by default | |
| Lazy by default | |
| Types before runtime | |
| The toolchain |
Pure by default
In Haskell a function maps arguments to a result and does nothing
else. It cannot read a clock, write a log line, or change a global
variable. The same input always produces the same output.
This is not a style rule that reviewers enforce. The type system
enforces it: a function whose signature contains no
IO cannot touch the outside world at all.
add :: Int -> Int -> Int
add a b = a + b
-- add 2 3 is 5, today and in ten years
Pure code is easy to test, because a test only needs the arguments. It is easy to refactor, because a call can be replaced by its result. It is easy to run in parallel, because two calls cannot fight over shared memory.
Lazy by default
Haskell evaluates an expression when somebody needs the value, not when the line is written. That makes infinite data structures ordinary values:
naturals = [1..]
take 5 naturals -- [1,2,3,4,5]
take 4 (map (*2) naturals) -- [2,4,6,8]
A pipeline of map and filter over a million elements runs in one pass and stops as soon as the consumer has enough. The price is memory, which the lesson on strictness deals with later.
Types before runtime
A program that compiles has no unhandled branch of a sum type, no null pointer from a missing value, and no accidental string where a number belongs. The compiler checks every signature and every branch before your first line runs.
describe :: Maybe Int -> String
describe Nothing = "no value"
describe (Just n) = "value is " ++ show n
Both cases are written down. If a branch is missing, the compiler warns; if a new constructor appears later, every incomplete match lights up at once.
The toolchain
Three programs carry the whole workflow. GHC compiles, GHCi is the interactive shell, and Cabal fetches dependencies and builds projects. GHCup installs all three and keeps versions side by side.
ghc --version
The Glorious Glasgow Haskell Compilation System, version 9.10.1
You need a terminal and about twenty minutes per lesson. Type every
example instead of reading it, because the compiler is the real
teacher here.
Next:
Install the toolchain with GHCup
Article author: Arthur Isaev