Hi everyone, I’ve been working through the OCaml CS3110 book, and I’m struggling to wrap my head around list pattern matching.
In the examples used, it shows how you can use the cons operator (::) to prepend elements to a list.
E.g.
let l = []
1 :: l
Which will output a list of ints [1].
It then goes on to talk about how you can get elements out of a list by using pattern matching. From my understanding this is taking an element/condition (?), and returning a value based on what it “matches”.
So, this makes sense to me:
let l = []
match l with
| [] -> "empty"
But then if this list has some elements, and say you want to just return the head of the list, you can do:
let l = [1; 2; 3]
match l with
| [] -> empty (* won't match *)
| h :: t -> h
I also understand that these are pattern variables which can be mapped to the element being matched.
But what I don’t understand is that a few lines previously I was told this is the cons operator which prepends to lists. But in this instance within the match statement it behaves differently.
I think I can understand what it’s doing: it takes [1; 2; 3] and puts 1 into h, and put’s the tail of the list into t. Is it just using the same syntax as list prepending, but actually has a different meaning here?