简体   繁体   中英

How to directly apply a function to the value of a match expression in F#

Assuming I have

let someFunction someVar =
  let x = 
    match someVar with
    | Value1 -> 10
    | Value2 -> 20
  anotherFunction x

Is there a way to directly apply "anotherFunction" to the return of the match expression without using the auxiliary "x" variable?

Yes, you can just apply it directly.

let someFunction someVar =
    anotherFunction( 
        match someVar with
        | Value1 -> 10
        | Value2 -> 20)

Like most other things in F#, match blocks are expressions that you can use inline if you think it improves your code. I'm not convinced it's preferable in this case though.

If the name of someVar is not important you can use function composition as a way to express the function:

let someFunction =
    function
    | Value1 -> 10
    | Value2 -> 20
    >> anotherFunction

The function keyword is syntactic sugar for fun x -> match x with... The >> operator takes a function and applies it to another function.

The existing answers show you how to do what you want, but if I was writing the code, I would just repeat the function call inside the match - I prefer that because it is placing "small expression" (function call) inside a "large expression" (pattern matching). The other way round, you end up with a large expression inside a small one, which makes the syntax less clear (in my view).

If you also use function to avoid someVar , it becomes a neat three-liner:

let someFunction = function
  | Value1 -> anotherFunction 10
  | Value2 -> anotherFunction 20

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM