Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F#, Pipe forward a match case without using temp variable

Tags:

I would like to pipe-forward a variable to a match case without using a temp variable or a lambda. The idea:

let temp =
    x 
    |> Function1
    |> Function2
    // ........ Many functions later.
    |> FunctionN

let result =
    match temp with
    | Case1 -> "Output 1"
    | Case2 -> "Output 2"
    | _ -> "Other Output"

I hope to write something similar to the following:

// IDEAL CODE (with syntax error)
let result =
    x
    |> Function1
    |> Function2
    // ........ Many functions later.
    |> FunctionN
    |> match with   // Syntax error here! Should use "match something with"
        | Case1 -> "Output 1"
        | Case2 -> "Output 2"
        | _ -> "Other Output"

The closest thing that I have is the following by using a lambda. But I think the code below is not really that great either, because I am still "naming" the temp variable.

let result =
    x
    |> Function1
    |> Function2
    // ........ Many functions later.
    |> FunctionN
    |> fun temp -> 
        match temp with   
        | Case1 -> "Output 1"
        | Case2 -> "Output 2"
        | _ -> "Other Output"

On the other hand, I can directly replace the "temp" variable with a big chunk of code:

let result =
    match x 
          |> Function1
          |> Function2
          // ........ Many functions later.
          |> FunctionN with
    | Case1 -> "Output 1"
    | Case2 -> "Output 2"
    | _ -> "Other Output"

Is it possible to write a code similar to Code #2? Or do I have to choose either Code #3 or #4? Thank you.

like image 593
CH Ben Avatar asked Nov 07 '17 06:11

CH Ben


1 Answers

let result =
    x
    |> Function1
    |> Function2
    // ........ Many functions later.
    |> FunctionN
    |> function  
        | Case1 -> "Output 1"
        | Case2 -> "Output 2"
        | _ -> "Other Output"
like image 198
hvester Avatar answered Oct 21 '22 03:10

hvester