What are some interesting uses of higher-order functions?

后端 未结 14 700
走了就别回头了
走了就别回头了 2021-01-30 00:55

I\'m currently doing a Functional Programming course and I\'m quite amused by the concept of higher-order functions and functions as first class citizens. However, I can\'t yet

14条回答
  •  没有蜡笔的小新
    2021-01-30 01:50

    Here's a pattern that I haven't seen anyone else mention yet that really surprised me the first time I learned about it. Consider a statistics package where you have a list of samples as your input and you want to calculate a bunch of different statistics on them (there are also plenty of other ways to motivate this). The bottom line is that you have a list of functions that you want to run. How do you run them all?

    statFuncs :: [ [Double] -> Double ]
    statFuncs = [minimum, maximum, mean, median, mode, stddev]
    
    runWith funcs samples = map ($samples) funcs
    

    There's all kinds of higher order goodness going on here, some of which has been mentioned in other answers. But I want to point out the '$' function. When I first saw this use of '$', I was blown away. Before that I hadn't considered it to be very useful other than as a convenient replacement for parentheses...but this was almost magical...

提交回复
热议问题