F# explicit match vs function syntax

后端 未结 8 2345
耶瑟儿~
耶瑟儿~ 2020-12-04 23:21

Sorry about the vague title, but part of this question is what these two syntax styles are called:

let foo1 x = 
    match x with
    | 1 -> \"one\"
    |         


        
相关标签:
8条回答
  • 2020-12-04 23:24

    The match version is called a "pattern matching expression". The function version is called a "pattern matching function". Found in section 6.6.4 of the spec.

    Using one over the other is a matter of style. I prefer only using the function version when I need to define a function that is only a match statement.

    0 讨论(0)
  • 2020-12-04 23:27

    function only allows for one argument but allows for pattern matching, while fun is the more general and flexible way to define a function. Take a look here: http://caml.inria.fr/pub/docs/manual-ocaml/expr.html

    0 讨论(0)
  • 2020-12-04 23:28

    They do the same thing in your case -- the function keyword acts like a combination of the fun keyword (to produce an anonymous lambda) followed by the match keyword.

    So technically these two are the same, with the addition of a fun:

    let foo1 = fun x ->
        match x with
        | 1 -> "one"
        | _ -> "not one"
    
    let foo2 = function
        | 1 -> "one"
        | _ -> "not one"
    
    0 讨论(0)
  • 2020-12-04 23:31

    Just for completeness sake, I just got to page 321 of Expert FSharp:

    "Note, Listing 12-2 uses the expression form function pattern-rules -> expression. This is equivalent to (fun x -> match x with pattern-rules -> expression) and is especially convenient as a way to define functions working directly over discriminated unions."

    0 讨论(0)
  • 2020-12-04 23:32

    The pro for the second syntax is that when used in a lambda, it could be a bit more terse and readable.

    List.map (fun x -> match x with | 1 -> "one" | _ -> "not one") [0;1;2;3;1]
    

    vs

    List.map (function 1 -> "one" | _ -> "not one") [0;1;2;3;1]
    
    0 讨论(0)
  • 2020-12-04 23:32

    The two syntaxes are equivalent. Most programmers choose one or the other and then use it consistently.

    The first syntax remains more readable when the function accepts several arguments before starting to work.

    0 讨论(0)
提交回复
热议问题