F#,在不使用临时变量的情况下向前传递匹配项 [英] F#, Pipe forward a match case without using temp variable
问题描述
我想在不使用temp变量或lambda的情况下将变量通过管道传递给匹配项.想法:
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"
我最接近的东西是使用lambda.但是我认为下面的代码也不是那么好,因为我仍在命名"临时变量.
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"
另一方面,我可以用大量代码直接替换"temp"变量:
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"
是否可以编写类似于代码2的代码?还是我必须选择代码3或代码4?谢谢.
Is it possible to write a code similar to Code #2? Or do I have to choose either Code #3 or #4? Thank you.
推荐答案
let result =
x
|> Function1
|> Function2
// ........ Many functions later.
|> FunctionN
|> function
| Case1 -> "Output 1"
| Case2 -> "Output 2"
| _ -> "Other Output"
这篇关于F#,在不使用临时变量的情况下向前传递匹配项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!