10

在 ML 系列语言中,人们倾向于使用模式匹配来if/else构建。在 F# 中,if/else在许多情况下,在模式匹配中使用守卫可以轻松替换。

例如,一个简单的delete1函数可以在不使用的情况下重写if/else(参见参考资料delete2):

let rec delete1 (a, xs) =
    match xs with
    | [] -> []
    | x::xs' -> if x = a then xs' else x::delete1(a, xs') 

let rec delete2 (a, xs) =
    match xs with
    | [] -> []
    | x::xs' when x = a -> xs'
    | x::xs' -> x::delete2(a, xs') 

另一个例子是求解二次函数:

type Solution =
    | NoRoot
    | OneRoot of float
    | TwoRoots of float * float

let solve1 (a,b,c) = 
    let delta = b*b-4.0*a*c
    if delta < 0.0 || a = 0.0 then NoRoot 
    elif delta = 0.0 then OneRoot (-b/(2.0*a))
    else 
        TwoRoots ((-b + sqrt(delta))/(2.0*a), (-b - sqrt(delta))/(2.0*a))

let solve2 (a,b,c) = 
    match a, b*b-4.0*a*c with
    | 0.0, _  -> NoRoot
    | _, delta when delta < 0.0 -> NoRoot
    | _, 0.0 -> OneRoot (-b/(2.0*a))
    | _, delta -> TwoRoots((-b + sqrt(delta))/(2.0*a),(-b - sqrt(delta))/(2.0*a))

我们应该使用带有守卫的模式匹配来忽略丑陋的if/else构造吗?

将模式匹配与警卫一起使用是否有任何性能影响?我的印象是它似乎很慢,因为在运行时检查了模式匹配。

4

4 回答 4

10

The right answer is probably it depends, but I surmise, in most cases, the compiled representation is the same. As an example

let f b =
  match b with
  | true -> 1
  | false -> 0

and

let f b =
  if b then 1
  else 0

both translate to

public static int f(bool b)
{
    if (!b)
    {
        return 0;
    }
    return 1;
}

Given that, it's mostly a matter of style. Personally I prefer pattern matching because the cases are always aligned, making it more readable. Also, they're (arguably) easier to expand later to handle more cases. I consider pattern matching an evolution of if/then/else.

There is also no additional run-time cost for pattern matching, with or without guards.

于 2011-11-02T20:18:08.700 回答
10

两者都有自己的位置。人们更习惯于使用 If/else 构造来检查一个值,因为模式匹配就像类固醇上的 If/else。模式匹配允许您对decomposed数据结构进行排序,并使用 gaurds 来指定分解数据部分或其他值的一些附加条件(特别是在递归数据结构或 F# 中所谓的区分联合的情况下) .

我个人更喜欢使用 if/else 进行简单的值比较(真/假、整数等),但如果您有递归数据结构或需要与其分解值进行比较的东西,那么没有比模式匹配更好的了。

首先使它工作并使其优雅和简单,然后如果您似乎有一些性能问题,然后检查性能问题(这主要是由于一些其他逻辑而不是由于模式匹配)

于 2011-11-03T05:47:12.637 回答
1

同意@Daniel 的观点,模式匹配通常更灵活。检查此实现:

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

另请注意https://fsharpforfunandprofit.com/learning-fsharp/不鼓励使用 if-else。它被认为是功能较少的投标。

于 2018-04-09T10:36:19.733 回答
0

我在一个自写的素数生成器上做了一些测试,据我所知,“if then else”比模式匹配慢得多,虽然无法解释为什么,但我已经测试了 imperativ在优化算法方面,F# 的一部分运行时间比递归函数样式慢。

于 2017-03-04T11:36:08.510 回答