Search code examples
functionhaskellfunctional-programmingcombinatorshigher-order-functions

What are some interesting uses of higher-order functions?


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 think of many practically useful, conceptually amazing, or just plain interesting higher-order functions. (Besides the typical and rather dull map, filter, etc functions).

Do you know examples of such interesting functions?

Maybe functions that return functions, functions that return lists of functions (?), etc.

I'd appreciate examples in Haskell, which is the language I'm currently learning :)


Solution

  • Well, you notice that Haskell has no syntax for loops? No while or do or for. Because these are all just higher-order functions:

     map :: (a -> b) -> [a] -> [b]
    
     foldr :: (a -> b -> b) -> b -> [a] -> b
    
     filter :: (a -> Bool) -> [a] -> [a]
    
     unfoldr :: (b -> Maybe (a, b)) -> b -> [a]
    
     iterate :: (a -> a) -> a -> [a]
    

    Higher-order functions replace the need for baked in syntax in the language for control structures, meaning pretty much every Haskell program uses these functions -- making them quite useful!

    They are the first step towards good abstraction because we can now plug custom behavior into a general purpose skeleton function.

    In particular, monads are only possible because we can chain together, and manipulate functions, to create programs.

    The fact is, life is pretty boring when it is first-order. Programming only gets interesting once you have higher-order.