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

前端 未结 4 790
予麋鹿
予麋鹿 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:23

    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.

提交回复
热议问题