What is 'Pattern Matching' in functional languages?

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

    Here is a really short example that shows pattern matching usefulness:

    Let's say you want to sort up an element in a list:

    ["Venice","Paris","New York","Amsterdam"] 
    

    to (I've sorted up "New York")

    ["Venice","New York","Paris","Amsterdam"] 
    

    in an more imperative language you would write:

    function up(city, cities){  
        for(var i = 0; i < cities.length; i++){
            if(cities[i] === city && i > 0){
                var prev = cities[i-1];
                cities[i-1] = city;
                cities[i] = prev;
            }
        }
        return cities;
    }
    

    In a functional language you would instead write:

    let up list value =  
        match list with
            | [] -> []
            | previous::current::tail when current = value ->  current::previous::tail
            | current::tail -> current::(up tail value)
    

    As you can see the pattern matched solution has less noise, you can clearly see what are the different cases and how easy it's to travel and de-structure our list.

    I've written a more detailed blog post about it here.

提交回复
热议问题