What task is best done in a functional programming style?

前端 未结 16 1731
-上瘾入骨i
-上瘾入骨i 2020-11-29 17:29

I\'ve just recently discovered the functional programming style and I\'m convinced that it will reduce development efforts, make code easier to read, make software more main

相关标签:
16条回答
  • 2020-11-29 17:47

    A simple example of a task that is often easiest done in a functional style is the transformation of data from one form to another. "Sum of squares" is a trivial example of data transformation. Luca's talk at last year's PDC showed how to use this sort of data transformation for something more practical, downloading and analyzing stock quotes. The demo is done in F#, but the concepts are the same and can be applied to C# or most other programming languages.

    http://channel9.msdn.com/pdc2008/TL11/

    0 讨论(0)
  • 2020-11-29 17:48

    Show them jQuery's way of iterating over DOM elements:

    $(".magic-divs").click(function(){
        // FYI, in this context, "this" will be the element clicked on.
        alert("somebody clicked on " + this.id);
        this.hide();
    
    });
    
    $(".magic-divs").show();
    

    vs. how most google results for "javascript element by classname" do it:

    var arrayOfElements = // this is filled with the elements somehow
    for(var i=0,j=arrayOfElements.length; i<j; i++) {
       alert("now I get to add an onclick event somehow " + i);
    }
    // i dont even want to type the ugly for-loop stuff to hide every div...
    

    Functional programming is useful in everyday stuff like the above!

    (note: I don't know if my example fits the exact definition of functional programming, but if it does, than functional programming is awesome)

    0 讨论(0)
  • 2020-11-29 17:49

    Tasks for functional style? Any time you have a common coding pattern and want to reduce it. A while ago I wrote a bit on using C# for functional style, while making sure it's practical: Practical Functional C# (I'm hesitate to link to my own stuff here, but I think it's relevant in this case). If you have a common "enterprise" application, showing, say, how expressions are lovely in pattern matching won't be too convincing.

    But in real-world apps, there are TONS of patterns that pop up at a low, coding level. Using higher order functions, you can make them go away. As I show in that set of blog posts, my favourite example is WCF's "try-close/finally-abort" pattern. The "try/finally-dispose" pattern is so common it got turned into a language keyword: using. Same thing for "lock". Those are both trivially represented as higher order functions, and only because C# didn't support them originally do we need hard-coded language keywords to support them. (Quick: switch your "lock" blocks out to use a ReaderWriter lock. Oops, we'll have to write a higher order function first.)

    But perhaps convincing just requires looking at Microsoft. Generics aka parametric polymorphism? That's hardly OO, but a nice functional concept that, now, everyone loves. The cute Ninject framework wouldn't work without it. Lambdas? As expression trees, they're how LINQ, Fluent NHibernate, etc. get all their power. Again, that doesn't come from OO or imperative programming. The new Threading library? Pretty ugly without closures.

    So, functional programming has been blessing things like .NET over the last decade. The major advances (such as generics, "LINQ") are directly from functional languages. Why not realise there's something to it and get more involved in it? That's how I'd phrase it to skeptics.

    The bigger problem is actually getting people to make the jump in understanding to higher order functions. While it's quite easy, if you've never seen it before in your life, it might be shocking an incomprehensible. (Heck, seems like a lot of people think generics are just for type-safe collections, and LINQ is just embedded SQL.)

    So, what you should do is go through your codebase, and find places that are an overly-complicated imperative nightmare. Search for the underlying patterns, and use functions to string it together nicely. If you can't find any, you might settle for just demo'ing off lists. For example "find all the Foos in this list and remove them". That's a 1 line thing in functional style "myList.Remove(x=>x.Bla > 0)" versus 7 lines in C# style (create a temp list, loop through and add to-remove items, loop though and remove the items).

    The hope is that, even though the syntax is odd, people will recognize "wow, that's a lot simpler". If they can put down the "verbose == more readable" and "that looks confusing" for a bit, you'll have a chance.

    Good luck.

    0 讨论(0)
  • 2020-11-29 17:50

    It's interesting noone has really answered the question: what task is best done in a "functional style"?

    A program/algorithm consists of 2 parts: logic control and data structure. I think the tasks best done in a functional style are those involved lists or arrays in cases where they behave like list (e.g. qsort). It's no coincidence that functional programming languages have very good support for lists.

    When the data structures deviate from lists, I think the use of a functional programming style become a little "unnatural".

    0 讨论(0)
  • 2020-11-29 17:51

    Algorithms involving backtracking search and simplifying undo support in GUIs are two places I've used functional style in practice.

    0 讨论(0)
  • 2020-11-29 17:52

    If by the 'functional style' you mean the usage of concepts like 'map', 'apply', 'reduce', 'filter', lambda functions and list comprehensions, then it should be evident that code that has to deal with operations on lists is almost always more concise when written in the 'functional style'. But if you're mixing 'functional style' with imperative code in a mostly imperative language, it really is just a matter of style.

    In python for example, you can reimplement the Haskell qsort crackmigg posted like so:

    def qsort(list):
        if list == []:
            return []
        else:
            x = list[0]; xs = list[1:]
            return qsort(filter(lambda y: y<x, xs)) + [x] + qsort(filter(lambda y: y>= x, xs))
    

    Although writing the last line as

    return qsort([y for y in xs if y<x]) + [x] + qsort([y for y in xs if y>=x])
    

    is arguably more 'pythonic'.

    But this is obviously more concise than the implementation here:

    http://hetland.org/coding/python/quicksort.html

    Which, incidentally, is how I would have thought about implementing it before I learned Haskell.

    The functional version is extremely clear if and only if you are acclimated to functional programming and grok what filter is going to do as easily as the well-worn C++ programmer groks a for loop without even having to think much about it. And that's clearly what the real issue at stake here: functional 'style' programming is a completely different mindset. If the people you work with aren't used to thinking recursively, and aren't the type to get excited about, not just a new technology, but a whole other way of thinking about solving their problems, then any amount of code comparisons isn't going to win them over.

    0 讨论(0)
提交回复
热议问题