I need to agree with simonuk. Although, as mentioned in the CMS, hd and tl are the correct functions, there are more arguments in this case.
When using pattern matching, you can use the compiler features to catch (basic) cases that you might have missed (for example, when the list is empty). You can probably catch or continue throwing this exception, but you do not need this, and you can introduce errors if this expectation does not occur often. Therefore, the habit of using pattern matching is good programming practice. For all purposes and tasks, the actual function is used when calling hd / tl IS that matches the pattern. In fact, in oamaml this is a failure:
let hd = function [] -> failwith "hd" | a::l -> a let tl = function [] -> failwith "tl" | a::l -> l
As an example, instead of using exceptions / crashes, we may find it more acceptable to use options :
> let car = function | hd::tl -> Some hd | _ -> None > let cdr = function | hd::[] -> None | hd :: tl -> Some tl | _ -> None
Also, be careful when using _ to match anything. It hurts more in options when you decide to add another type ... opps!
source share