How does pattern matching work behind the scenes in F#?

前端 未结 4 1287
花落未央
花落未央 2021-02-12 13:25

I am completely new to F# (and functional programming in general) but I see pattern matching used everywhere in sample code. I am wondering for example how pattern matching actu

4条回答
  •  无人共我
    2021-02-12 13:36

    No, it doesn't loop. If you have a pattern match like this

    match x with
    | Foo a b -> a + b
    | Bar c -> c
    

    this compiles down to something like this pseudo code:

    if (x is a Foo)
      let a = (first element of x) in
      let b = (second element of x) in
      a+b
    else if (x is a Bar)
      let c = (first element of x) in
      c
    

    If Foo and Bar are constructors from an algebraic data type (i.e. a type defined like type FooBar = Foo int int | Bar int) the operations x is a Foo and x is a Bar are simple comparisons. If they are defined by an active pattern, the operations are defined by that pattern.

提交回复
热议问题