문제

So I have this sample piece of code, and I want to add a try-with block inside it:

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)

The try-with block I want to add should just wrap the call to List.fold, however if I do wrap only that line, then I cannot access the variable theImportantLocalVar later.

For now, as a workaround, I have put the try-with block wrapping the whole function body (except the first line about assigning someLocalVar), but I would like to avoid this:

static member private SomeFunc
    (someParam: list<DateTime*int>) =

    let someLocalVar = helpers.someOtherFunc someParam

    try
        let theImportantLocalVar =
            List.fold
                helpers.someFoldFunc
                ([],someLocalVar.First())
                someLocalVar.Tail

        let first = fst theImportantLocalVar

        let tail = someParam.Tail

        helpers.someLastFunc(first,tail,theImportantLocalVar)

    with
    | BadData(_) -> raise (new
        ArgumentException("output values can only increase: " + someLocalVar,
                          "someParam"))

In C#, I would have solved it with a bool exception=false that I would turn into true inside the catch block (to later query it in the second part of the function), or initializing theImportantLocalVar with null to compare it later; however, in F# for this I would need the mutable keyword, something that is discouraged.

So how to do this without using a mutable variable?

도움이 되었습니까?

해결책

try/with is an expression, so you can do this:

let theImportantLocalVar =
    try
        List.fold
            helpers.someFoldFunc
            ([],someLocalVar.First())
            someLocalVar.Tail
    with
    | BadData(_) -> raise (new
        ArgumentException("output values can only increase: " + someLocalVar,
                          "someParam"))
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top