Jane Street OCaml Challenge: Lists
OCaml natively supports linked lists. The syntax:
[]
represents the empty list
hd :: tl
prepends an element to the front of a list
Here's a list equality test using ::
:
let () = assert ([%compare.equal: int list] [5; 1; 8; 4] (5 :: 1 :: 8 :: 4 :: []))
List Length
let rec length lst =
match lst with
| [] -> 0
| _ :: tl -> 1 + length tl
Your Turn: Sum of List
Use pattern matching to compute the sum of a list.
let rec sum lst = failwith "For you to implement"
List Operators
(@)
appends two lists:
let list_append first second = first @ second
(::)
prepends an element to a list:
let new_head hd rest = hd :: rest
Tests for sum
let%test "Testing sum..." = Int.( = ) 0 (sum [])
let%test "Testing sum..." = Int.( = ) 55 (sum [ 55 ])
let%test "Testing sum..." = Int.( = ) 0 (sum [ 5; -5; 1; -1 ])
let%test "Testing sum..." = Int.( = ) 12 (sum [ 5; 5; 1; 1 ])