Pattern matching with guards vs if/else construct in F#

前端 未结 4 813
予麋鹿
予麋鹿 2021-01-12 08:24

In ML-family languages, people tend to prefer pattern matching to if/else construct. In F#, using guards within pattern matching could easily replace if/e

4条回答
  •  自闭症患者
    2021-01-12 09:10

    Agree with @Daniel that pattern matching is usually more flexible. Check this implementation:

    type Solution = | Identity | Roots of float list
    
    let quadraticEquation x =
    
        let rec removeZeros list =
            match list with
            | 0.0::rest -> removeZeros rest
            | _ -> list
        let x = removeZeros x
    
        match x with
        | [] -> Identity // zero constant
        | [_] -> Roots [] // non-zero constant
        | [a;b] -> Roots [ -b/a ] // linear equation
        | [a;b;c] ->
            let delta = b*b - 4.0*a*c
            match delta with
            | delta when delta < 0.0 -> 
                Roots [] // no real roots
            | _ ->
                let d = sqrt delta
                let x1 = (-b-d) / (2.0*a)
                let x2 = (-b+d) / (2.0*a)
                Roots [x1; x2]
        | _ -> failwithf "equation is bigger than quadratic: %A" x
    

    Also notice in https://fsharpforfunandprofit.com/learning-fsharp/ that it is discouraged to use if-else. It is considered a bid less functional.

提交回复
热议问题