What is 'Pattern Matching' in functional languages?

后端 未结 9 533
栀梦
栀梦 2020-11-30 16:43

I\'m reading about functional programming and I\'ve noticed that Pattern Matching is mentioned in many articles as one of the core features of functional languages.

9条回答
  •  孤独总比滥情好
    2020-11-30 17:05

    It means that instead of writing

    double f(int x, int y) {
      if (y == 0) {
        if (x == 0)
          return NaN;
        else if (x > 0)
          return Infinity;
        else
          return -Infinity;
      } else
         return (double)x / y;
    }
    

    You can write

    f(0, 0) = NaN;
    f(x, 0) | x > 0 = Infinity;
            | else  = -Infinity;
    f(x, y) = (double)x / y;
    

    Hey, C++ supports pattern matching too.

    static const int PositiveInfinity = -1;
    static const int NegativeInfinity = -2;
    static const int NaN = -3;
    
    template  struct Divide {
      enum { value = x / y };
    };
    template  struct aux { enum { value = PositiveInfinity }; };
    template <> struct aux { enum { value = NegativeInfinity }; };
    template  struct Divide {
      enum { value = aux<(x>0)>::value };
    };
    template <> struct Divide<0, 0> {
      enum { value = NaN };
    };
    
    #include 
    
    int main () {
        printf("%d %d %d %d\n", Divide<7,2>::value, Divide<1,0>::value, Divide<0,0>::value, Divide<-1,0>::value);
        return 0;
    };
    

提交回复
热议问题