Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does function [x] -> ... work

Tags:

f#

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.

like image 968
egerhard Avatar asked Dec 19 '22 15:12

egerhard


2 Answers

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.

like image 55
Lee Avatar answered Jan 03 '23 18:01

Lee


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.

like image 40
latkin Avatar answered Jan 03 '23 19:01

latkin