Skip to content
Snippets Groups Projects
Select Git revision
  • c66c2e02adcdd890b11aa3841fcbe2f0e26b304b
  • main default protected
2 results

04-first-types.md

Blame
  • Nicolas Lenz's avatar
    Nicolas Lenz authored
    c66c2e02
    History
    Code owners
    Assign users and groups as approvers for specific file changes. Learn more.

    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

    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