How the function [x] -> ... works

I was looking at the source code for FSharp.Data when I came across this line of code

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

function [l]I do not understand. In particular, I do not understand how the parameter works [l].

From experiments in FSI, I can determine that it launches a pattern matching form similar to that match [l] with .... However, I cannot understand how the F # compiler interprets this expression.

What I would like to know is how it works and what rules it follows.

+4
source share
2 answers

See documents in template matching syntax . function- shorthand syntax for accepting a single argument and immediately matching the pattern:

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

Is the equivalent

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

, function , , . , :

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

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

Edit: ( ) [l], , . , , , l. . " " .

+2

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

, .

+9

Source: https://habr.com/ru/post/1537206/


All Articles