尝试使用F#中较小的块?
我有这段代码示例,我想在其中添加一个try-with块:尝试使用F#中较小的块?,f#,try-catch,immutability,c#-to-f#,F#,Try Catch,Immutability,C# To F#,我有这段代码示例,我想在其中添加一个try-with块: static member private SomeFunc (someParam: list<DateTime*int>) = let someLocalVar = helpers.someOtherFunc someParam let theImportantLocalVar = List.fold helpers.someFoldFunc
static member private SomeFunc
(someParam: list<DateTime*int>) =
let someLocalVar = helpers.someOtherFunc someParam
let theImportantLocalVar =
List.fold
helpers.someFoldFunc
([],someLocalVar.First())
someLocalVar.Tail
let first = fst theImportantLocalVar
let tail = someParam.Tail
helpers.someLastFunc(first,tail,theImportantLocalVar)
在C#中,我会使用bool exception=false来解决它,我会在catch块内将其转换为true
(稍后在函数的第二部分中查询它),或者使用null初始化importantLocalVar,以便稍后进行比较;然而,在F#中,我需要mutable
关键字,这是不鼓励的
那么,如何在不使用可变变量的情况下做到这一点呢
try
/with
是一个表达式,因此可以执行以下操作:
let theImportantLocalVar =
try
List.fold
helpers.someFoldFunc
([],someLocalVar.First())
someLocalVar.Tail
with
| BadData(_) -> raise (new
ArgumentException("output values can only increase: " + someLocalVar,
"someParam"))
let theImportantLocalVar =
try
List.fold
helpers.someFoldFunc
([],someLocalVar.First())
someLocalVar.Tail
with
| BadData(_) -> raise (new
ArgumentException("output values can only increase: " + someLocalVar,
"someParam"))