// Standard pattern matching.
let Foo x =
match x with
| 1 ->
// ... lots of code, only evaluated if x == 1
| 2 ->
// ... lots of code, only evaluated if x == 2
// Standard pattern matching separated out, causing exception.
let Bar x =
let valueOne = //... lots of code, evaluated always. Exception if value <> 1.
let valueTwo = //... lots of code, evaluated always. Exception if value <> 2.
match x with
| 1 -> valueOne
| 2 -> valueTwo
在使用“匹配”的模式匹配中,每个模式的代码可能很大,参见上面的Foo,这让我想将块拆分为单独的调用以提高可读性。
这样做的问题可能是即使模式不匹配,也会评估调用,如上面的Bar所示。
- 选项 1:惰性评估。
- 选项 2:转发参数/参数。
- 选项 3:转发参数/参数并使用 Active 模式。
在每种模式下的代码可能很大的情况下,提高可读性的首选方法是什么。或者还有其他明显的解决方案吗?
// ===== OPTION 1 =====
// Pattern matching separated out, lazy eval.
let Foo x =
let valueOne = lazy //... lots of code, evaluated on Force().
let valueTwo = lazy //... lots of code, evaluated on Force().
match x with
| 1 -> valueOne.Force()
| 2 -> valueTwo.Force()
// ===== OPTION 2 =====
// Pattern matching separated out, with arguments.
let Foo x =
let valueOne a = //... lots of code.
let valueTwo a = //... lots of code.
match x with
| 1 -> valueOne x
| 2 -> valueTwo x
// ===== OPTION 3 =====
// Active Pattern matching separated out, with arguments.
let Foo x =
let (|ValueOne|_|) inp =
if inp = 1 then Some(...) else None
let (|ValueTwo|_|) inp =
if inp = 2 then Some(...) else None
match x with
| ValueOne a -> a
| ValueTwo b -> b