Lesson 8 of 15
Lists
Lists
OCaml lists are immutable, singly-linked, and homogeneous. Create them with square brackets and semicolons:
let nums = [1; 2; 3; 4; 5]
Basic Operations
let first = List.hd nums (* 1 *)
let rest = List.tl nums (* [2; 3; 4; 5] *)
let len = List.length nums (* 5 *)
let third = List.nth nums 2 (* 3 *)
Cons Operator (::)
Prepend an element to a list:
let more = 0 :: nums (* [0; 1; 2; 3; 4; 5] *)
Append (@)
let combined = [1; 2] @ [3; 4] (* [1; 2; 3; 4] *)
Your Task
Write a recursive function sum_list that computes the sum of a list of integers.
JS Transpiler loading...
Loading...
Click "Run" to execute your code.