What is 'Pattern Matching' in functional languages?

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

    Pattern matching is where the interpreter for your language will pick a particular function based on the structure and content of the arguments you give it.

    It is not only a functional language feature but is available for many different languages.

    The first time I came across the idea was when I learned prolog where it is really central to the language.

    e.g.

    last([LastItem], LastItem).

    last([Head|Tail], LastItem) :- last(Tail, LastItem).

    The above code will give the last item of a list. The input arg is the first and the result is the second.

    If there is only one item in the list the interpreter will pick the first version and the second argument will be set to equal the first i.e. a value will be assigned to the result.

    If the list has both a head and a tail the interpreter will pick the second version and recurse until it there is only one item left in the list.

提交回复
热议问题