Understanding pattern matching with cons operator

Posted by Mathias on Stack Overflow See other posts from Stack Overflow or by Mathias
Published on 2010-05-17T04:01:37Z Indexed on 2010/05/17 4:20 UTC
Read the original article Hit count: 332

Filed under:
|
|

In "Programming F#" I came across a pattern-matching like this one (I simplified a bit):

let rec len list = 
  match list with
  | [] -> 0
  | [_] -> 1
  | head :: tail -> 1 + len tail;;

Practically, I understand that the last match recognizes the head and tail of the list. Conceptually, I don't get why it works. As far as I understand, :: is the cons operator, which appends a value in head position of a list, but it doesn't look to me like it is being used as an operator here. Should I understand this as a "special syntax" for lists, where :: is interpreted as an operator or a "match pattern" depending on context? Or can the same idea be extended for types other than lists, with other operators?

© Stack Overflow or respective owner

Related posts about F#

Related posts about pattern-matching