Topics in Advanced Computing Lesson 1: Lists

  1. Questions
    1. Reminders
    2. Set Up
  2. Lists
    1. Ranges
    2. Implementation questions
    3. Comprehensions
    4. Exercise

Questions

Reminders

Set Up

Lists

Ranges

Infinite lists:

Implementation questions

Comprehensions

ghci> [x+1 | x <- [0,2..10]]
[1,3,5,7,9,11]

The vertical bar is like the set-theoretic “such that”. “List of all the numbers x + 1, such that x is in the set [0, 2..10]”

Even squares:

ghci> evenSquares = [ x*x | x <- [0,2..]]
take 10 evenSquares
[0,4,16,36,64,100,144,196,256,324]

More than one condition? Even squares that are multiples of 3?

ghci> evenMult3Squares = [x | y <- [0,2..], let x = y * y, x mod 3 == 0]
ghci> take 10 evenMult3Squares
[0,36,144,324,576,900,1296,1764,2304,2916]

let keyword?

Exercise: Can we make an infinite list of all Pythagorean triples? A Pythagorean triple is a tuple $(x, y, z)$ such that $x^2 + y^2 = z^2$. We can restrict these to just be of the form $x < y < z$, so that $(3, 4, 5)$ shows up but $(4, 3, 5)$ does not.

Solution

pythTrips = [(x,y,z) | z <- [1..], y <- [1..z], x <- [1..y], x^2 + y^2 == z^2]

Aside: tuples?

Exercise

The handshake problem: given $n$ people in a room, if everyone shakes hands with everyone else, how many handshakes are there?

Define a function handshakes n which returns a list of unique ordered pairs $(x, y)$ such that $x \neq y$, and $x < y$.

Use it so that:

ghci> handshakes 4
[(1, 2),(1,3),(1,4),(2,3),(2,4),(3,4)]

To start you out:

handshakes n = 

Fill in the rest!