Lab 13

Lab 13 Instructions #

Reminders #

  • While students are coming into class, feel free to go ahead and download the lab materials in preparation for the start of the lab proper. (But please wait until you’re instructed before beginning work on the lab.)

  • Don’t move on from a problem until the lab group members agree. If you “get it” ahead of the others in your lab group, you can help your own understanding by explaining things to them.

  • Swap laptops and driver after each problem.

  • We post lab solutions with extra information and ways of solving.

  • Do you have hints or tips about the course? Let us know: heads@cs51.io.

Setup instructions #

Head to http://url.cs51.io/lab13 and follow the Lab Procedures.

Lab puzzle #

We can count the number of 1s in a list using the following function:

# let how_many_ones (lst : int list) : int =
    let open List in
    length (filter ((=) 1) lst) ;;
val how_many_ones : int list -> int = <fun>
# how_many_ones [0; 2; 1; 1; 2; 1] ;;
- : int = 3

Now consider the following definition of a loopy function func : int list -> int:

# let func (x : int) : int list =
    let a = ref 0 in
    let lst = ref [] in
    while !a < x do
      lst := !lst @ [!a];
      lst := !lst @ !lst;
      a := succ !a
    done;
    !lst ;;
val func : int -> int list = <fun>

What is the value of how_many_ones (func 4)?

  • 0
  • 1
  • 2
  • 3
  • 4
  • 6
  • 8
  • 12
  • 16
  • 32