Haskell, lesson 2
In most languages a variable is a box whose contents change. Haskell is different: a name is bound to a value once, and it means that value forever. There is no assignment that overwrites it. This sounds limiting, but it means a name can never surprise you by changing behind your back.
These are top-level definitions. The line with :: is the type signature; the line with
= gives the value. Writing level = 8 a second time in the same file is an error, not an
update.
| Type | Holds | Example |
|---|---|---|
Int | whole numbers (64-bit) | 42 |
2 exercises to try what you just read.
Integer |
| whole numbers of any size |
2 ^ 100 |
Double | numbers with a decimal point | 3.5 |
Bool | True or False (capital letters) | True |
Char | one character, in single quotes | 'A' |
String | text, in double quotes | "tea" |
A String is really a list of Char, which is why many list functions work on text too.
Haskell never converts between types silently. You cannot add an Int to a Double
directly; you convert first with fromIntegral. We will use that in the next lesson.
Names of values and functions start with a lowercase letter and usually use camelCase:
maxHealth, totalPrice. Names that start with an uppercase letter are reserved for types
and constructors, like Int and True. A trailing apostrophe is allowed and common for a
"next version" of something: score'.
Inside main you can introduce local names with let:
Several bindings in one let must line up under each other. Outside a do block you can
attach local names to a definition with where, which reads like a footnote:
++ joins two strings. It only works on strings, so a number must first be turned into
text with show:
Don't show a string you want to display as-is, because show "tea" includes the quotes.
When you need an updated value, you make a new name for it:
start is still 20. This style, building new values from old ones instead of changing them,
is at the heart of functional programming.
The starter defines four values for a game character. Print them on one line in exactly this format:
Use ++ and show. The program reads no input.
Savings start at 20. Instead of changing one variable, create a new name for each step:
afterDeposit adds a deposit of 15.doubled doubles that.afterSnack spends 8.Print every step:
playerName :: String
playerName = "Rowan"
level :: Int
level = 7main :: IO ()
main = do
let cups = 3
item = "tea"
putStrLn (show cups ++ " cups of " ++ item)area :: Double
area = width * height
where
width = 4.0
height = 2.5main :: IO ()
main = do
let score = 12 :: Int
putStrLn ("Score: " ++ show score) -- Score: 12
putStrLn ("Mage? " ++ show True) -- Mage? Truelet start = 20
later = start + 5Rowan | level 7 | 42.5 HP | mage: TrueStart: 20
After deposit: 35
Doubled: 70
After snack: 62