F# explicit match vs function syntax

后端 未结 8 2446
耶瑟儿~
耶瑟儿~ 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:36

    The function version is a short hand for the full match syntax in the special case where the match statement is the entire function and the function only has a single argument (tuples count as one). If you want to have two arguments then you need to use the full match syntax*. You can see this in the types of the following two functions.

    //val match_test : string -> string -> string
    let match_test x y = match x, y with
                            | "A", _ -> "Hello A"
                            | _, "B" -> "Hello B"
                            | _ -> "Hello ??"
    
    //val function_test : string * string -> string                   
    let function_test = function
                            | "A", _ -> "Hello A"
                            | _, "B" -> "Hello B"
                            | _ -> "Hello ??"
    

    As you can see match version takes two separate arguments whereas the function version takes a single tupled argument. I use the function version for most single argument functions since I find the function syntax looks cleaner.

    *If you really wanted to you can get the function version to have the right type signature but it looks pretty ugly in my opinion - see example below.

    //val function_match_equivalent : string -> string -> string
    let function_match_equivalent x y = (x, y) |> function
                                                    | "A", _ -> "Hello A"
                                                    | _, "B" -> "Hello B"
                                                    | _ -> "Hello ??"
    
    0 讨论(0)
  • 2020-12-04 23:49

    This is an old question but I will throw my $0.02.

    In general I like better the match version since I come from the Python world where "explicit is better than implicit."

    Of course if type information on the parameter is needed the function version cannot be used.

    OTOH I like the argument made by Stringer so I will start to use function in simple lambdas.

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