Select Git revision
04-first-types.md

Nicolas Lenz authored
Code owners
Assign users and groups as approvers for specific file changes. Learn more.
04-first-types.md 1.18 KiB
First Types
What is a Type?
- "Classifies" values
- Constrains what a value can be
Basic Types in Haskell
-
Int
: Integer numbers (-1
,0
,30
) -
Bool
: Truth values (True
,False
) (capitalized!) -
Char
: Single characters ('a'
,'c'
) -
String
: Text ("Hello"
,"Cheese sandwich"
) -
a -> b
: Function with- the input type (domain)
a
- the output type (codomain or range)
b
- the input type (domain)
Specifying a Type
x :: Int
x = 5
favoriteAnimal :: String
favoriteAnimal = "Cat, obviously"
firstLetter :: Char
firstLetter = 'A'
double :: Int -> Int
double x = x * 2
Recommendation: Always specify the type.
Lists
Ordered list with elements of type a
: [a]
fruits :: [String]
fruits = ["Banana", "Apple", "Raspberry"]
numbers :: [Int]
numbers = [1,5,2]
empty :: [Int]
empty = []
Building Lists
Lists are a recursive data structure
A list is always one of two things:
-
an empty list:
[]
-
an element added in front of another list:
element : list
These are all the same list:
[1, 2, 3]
1 : [2, 3]
1 : (2 : (3 : []))
1 : 2 : 3 : []
moreFruits :: [String]
moreFruits = "Orange" : fruits