What is 'Pattern Matching' in functional languages?

后端 未结 9 535
栀梦
栀梦 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:24

    Short answer: Pattern matching arises because functional languages treat the equals sign as an assertion of equivalence instead of assignment.

    Long answer: Pattern matching is a form of dispatch based on the “shape” of the value that it's given. In a functional language, the datatypes that you define are usually what are known as discriminated unions or algebraic data types. For instance, what's a (linked) list? A linked list List of things of some type a is either the empty list Nil or some element of type a Consed onto a List a (a list of as). In Haskell (the functional language I'm most familiar with), we write this

    data List a = Nil
                | Cons a (List a)
    

    All discriminated unions are defined this way: a single type has a fixed number of different ways to create it; the creators, like Nil and Cons here, are called constructors. This means that a value of the type List a could have been created with two different constructors—it could have two different shapes. So suppose we want to write a head function to get the first element of the list. In Haskell, we would write this as

    -- `head` is a function from a `List a` to an `a`.
    head :: List a -> a
    -- An empty list has no first item, so we raise an error.
    head Nil        = error "empty list"
    -- If we are given a `Cons`, we only want the first part; that's the list's head.
    head (Cons h _) = h
    

    Since List a values can be of two different kinds, we need to handle each one separately; this is the pattern matching. In head x, if x matches the pattern Nil, then we run the first case; if it matches the pattern Cons h _, we run the second.

    Short answer, explained: I think one of the best ways to think about this behavior is by changing how you think of the equals sign. In the curly-bracket languages, by and large, = denotes assignment: a = b means “make a into b.” In a lot of functional languages, however, = denotes an assertion of equality: let Cons a (Cons b Nil) = frob x asserts that the thing on the left, Cons a (Cons b Nil), is equivalent to the thing on the right, frob x; in addition, all variables used on the left become visible. This is also what's happening with function arguments: we assert that the first argument looks like Nil, and if it doesn't, we keep checking.

提交回复
热议问题