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

两盒软妹~` 提交于 2019-12-10 01:50:05

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/47151551/f-pipe-forward-a-match-case-without-using-temp-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!