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

前端 未结 4 544
栀梦
栀梦 2021-02-12 13:02

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:47

    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.

提交回复
热议问题