How can I refactor out the required else clause?

后端 未结 6 469
春和景丽
春和景丽 2021-01-12 09:13

I have a C# method that looks a bit like this:

bool Eval() {
  // do some work
  if (conditionA) {
     // do some work
     if (conditionB) {
       // do s         


        
6条回答
  •  无人及你
    2021-01-12 09:55

    Using the higher-order functions in the Option module can make this flow very cleanly without any mutable state:

    let Eval () =
        // do some work
        if not conditionA then None else
            // do some work
            Some state
        |> Option.bind (fun state ->
            if not conditionB then None else
                // do some work
                Some state')
        |> Option.bind (fun state ->
            if not conditionC then None else
                // do some work
                Some true)
        |> defaultArg <| false
    

    Or for further clarity, using named functions rather than lambdas:

    let Eval () =
        let a () =
            if not conditionA then None else
                // do some work
                Some state
        let b state =
            if not conditionB then None else
                // do some work
                Some state'
        let c state =
            if not conditionC then None else
                // do some work
                Some true
        // do some work
        a () |> Option.bind b |> Option.bind c |> defaultArg <| false
    

提交回复
热议问题