Homework 1: Getting Started with OCaml

First submission: Thursday, August 24th, at 11:59 PM

Second submission: Tuesday, August 29th, at 11:59 PM

Setting up

The goal of this assignment is to set up the tools you need for the class, and get a feel for the OCaml programming language. If you have questions or get stuck, you can always ask for help on Piazza.

The first step is to set up OCaml on your computer. You can find instructions at https://ocaml.org/docs/up-and-running. If you’re using Windows and don’t already have WSL installed, the easiest way is probably to use the OCaml for Windows installer linked from that page. Once you’re done, make sure that you can run ocaml as described in “The OCaml top level”.

Once you have OCaml installed, you’ll want an IDE to use with it. I recommend Visual Studio Code with the OCaml Platform extension. You can find installation instructions under “Configuring Your Editor”. If you have another editor you’re already used to, you can use that instead – it almost certainly has an OCaml extension. If you have any trouble setting up OCaml or your editor, post on Piazza or email me and we’ll figure it out.

Problems

Download the file hw1-base.ml, open it in your editor, and rename it to hw1.ml. Then fill in the code for the following functions:

  1. (3 points) A function called sum_range that takes two ints, min and max, and returns the sum of the numbers from min to max (including both min and max). For instance, sum_range 3 6 should return 3 + 4 + 5 + 6 = 18. Your solution should use recursion, not a loop!

  2. (3 points) A function called sub2 that takes a tuple of ints (that is, a value of type int * int) and subtracts the first from the second. For instance, sub2 (3, 4) should return 1. (Hint: you can use the functions fst and snd to access the elements of a tuple.)

  3. (3 points) An inductive datatype called tree that is either a Leaf with an int value, or a Node with two subtrees (each of type tree).

  4. (1 point) A variable called my_tree that is of type tree. It can be any tree you want, it just has to typecheck!

  5. (4 points) A function called tree_sum that takes a tree and returns the sum of all the ints in it. Also, try running tree_sum on my_tree and make sure it gives the result you expect!

Testing your code

In the OCaml REPL, you can run #use "hw1.ml";; to load and execute the functions you’ve defined. This will also print the results of some simple test cases. Once you’ve #used the file, you can run more tests of your own. When you’re done, submit your hw1.ml on Gradescope.

If you get stuck, you can post a question on Piazza or come to office hours. If you want more practice with OCaml, try the tutorials at https://ocaml.org/learn/.