Question

I was browsing through the source code for FSharp.Data when I came across this line of code

let (|Singleton|) = function [l] -> l | _ -> failwith "Parameter mismatch"

The function [l] is what I don't understand. More specifically, I don't understand how the [l] parameter works.

From experimenting in the FSI, I can determine that it starts a form of pattern matching similar to match [l] with .... However, I can't figure out how the F# compiler interprets the expression.

What I'd like to know is how it actually works and what rules it follows.

Was it helpful?

Solution 2

See the docs on pattern matching syntax. function is a shorthand syntax for taking a single argument and immediately pattern matching:

let foo x =
    match x with
    | CaseA -> 1
    | CaseB -> 2

Is the equivalent of

let foo = function
    | CaseA -> 1
    | CaseB -> 2

Note that function just adds one argument, it doesn't enforce that there is exactly one argument. For example, this is acceptable:

let foo x y = function
  | CaseA -> x + y
  | CaseB -> x - y

And is equivalent to

let foo x y z = 
  match z with
  | CaseA -> x + y
  | CaseB -> x - y

Edit: (For completeness) And as for [l], like Lee said, that's just a match pattern. Specifically, a structural match pattern on lists which matches lists with a single element, and binds that element to the identifier l. See "List Pattern" here.

OTHER TIPS

It is equivalent to

let (|Singleton|) lst =
    match lst with
    | [l] -> l
    | _ -> failwith "Parameter mismatch"

so it extracts the element from a single-element list or throws an exception if the list has any other number of elements.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top