Work on this exercise locally

This web app is a reference guide — you can read instructions, browse starter code, and view tests here. To actually complete the exercise, you need to work in your local development environment.

1Clone the repo: git clone https://github.com/weihaoqu/program-analysis-bootcamp-student
2Edit the starter file in your editor (VS Code, Vim, etc.) — replace failwith "TODO" with your implementation.
3Run the tests: dune runtest modules/module0-warmup/exercises/ocaml-basics

OCaml Basics

3. Exercise 1: OCaml Basics (~20 min)

File: exercises/ocaml-basics/starter/main.ml Run:

dune exec modules/module0-warmup/exercises/ocaml-basics/starter/main.exe

What You'll Implement

FunctionWhat It DoesConcept
squareReturns x * xBasic function
is_emptyChecks if string is emptyString.length
greetReturns "Hello, name!"String concatenation
is_digitChecks if char is '0'..'9'Char comparison
is_alphaChecks if char is letter/underscoreMultiple ranges
classify_charReturns "digit"/"alpha"/"operator"/"unknown"Using helper functions
format_tokenFormats a (category, text) tupleTuple destructuring
make_tokenCreates token from text stringString indexing
format_posFormats a (line, col) positionPrintf.sprintf
advance_posUpdates position after reading a charNewline handling

Hints

  • String.length s returns the length of s.
  • s.[0] returns the first character of string s.
  • Printf.sprintf "line %d, col %d" line col creates a formatted string.
  • Characters can be compared with <=: '0' <= c && c <= '9'.

Expected Output

=== Exercise 1: OCaml Basics ===

square 5 = 25
square (-3) = 9
is_empty "" = true
is_empty "hi" = false
greet "OCaml" = Hello, OCaml!

classify_char '7' = digit
classify_char 'x' = alpha
classify_char '+' = operator
classify_char '!' = unknown

format_token ("keyword", "if") = [keyword: if]
make_token "42" = [number: 42]
make_token "hello" = [identifier: hello]
make_token "+" = [symbol: +]
make_token "" = [empty: ]

format_pos (1, 1) = line 1, col 1
advance_pos (1,1) 'a' = line 1, col 2
advance_pos (1,3) '\n' = line 2, col 1
scan_positions "ab\ncd" = line 2, col 3

Done!