I am trying to understand what this block of code is doing:
let rec size x =
match x with
[] -> 0
| _::tail -> 1 + (size tail) ;;
I know that this expression computes the size of a list, but I don’t understand where in the code it reduces the list one by one. For example, I think it needs to go from [1;2;3] to [2;3] to [3], but where or how does it do it? I don’t get it.
Thanks.
A list in OCaml is built recursively using empty list (
[]) and cons (::) constructor. So[1; 2; 3]is a syntactic sugar of1::2::3::[].The size is computed by reducing
xin each step using the pattern_::tail(_denotes that we ignore the head of the list) and calling the same functionsizeontail. The function eventually terminates when the list is empty and the pattern of[]succeeds.Here is a short illustration of how
size [1; 2; 3]is computed:As a side note, you can see from the figure that a lot of information needs to be stored in the stack to compute
size. That means your function could result in a stack overflow error if the input list is long, but it is another story.