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:
-
(3 points) A function called
sum_range
that takes twoint
s,min
andmax
, and returns the sum of the numbers frommin
tomax
(including bothmin
andmax
). For instance,sum_range 3 6
should return 3 + 4 + 5 + 6 = 18. Your solution should use recursion, not a loop! -
(3 points) A function called
sub2
that takes a tuple ofint
s (that is, a value of typeint * int
) and subtracts the first from the second. For instance,sub2 (3, 4)
should return 1. (Hint: you can use the functionsfst
andsnd
to access the elements of a tuple.) -
(3 points) An inductive datatype called
tree
that is either aLeaf
with anint
value, or aNode
with two subtrees (each of typetree
). -
(1 point) A variable called
my_tree
that is of typetree
. It can be any tree you want, it just has to typecheck! -
(4 points) A function called
tree_sum
that takes atree
and returns the sum of all theint
s in it. Also, try runningtree_sum
onmy_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 #use
d 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/.