What are some good examples that I can use to explain functional programming?
The audience would be people with little programming experience, or people who only have object-oriented experience.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Is it really possible to explain functional programming, let along OO or procedural or any paradigm of programming to people without much programming experience?
Well probably the best examples would be converting known design patterns into their functional equivalent. Let’s take the canonical example of converting a list of ints to a list of strings:
Its simple, readable, object-oriented, its even generic so it works for any arbitrary types, so what’s the problem? For a start, its bloated: I have an interface definition and two interface implementations. What if I need another conversion? Well, I need another interface implementation — it can get out of hand quickly.
When you think about it, the
IConvertor<T, U>class is just a wrapper around a single function calledConvert— the class literally exists to help us passConvertto other functions. If you can understand this much, then you already understand the basic principles behind functions as first-class values — functional programming is all about passing functions to other functions in pretty much the same way you pass a person or an int or a string.People usually prefer functional programming because it helps them avoid single-method interfaces and implementations. Instead of passing a class, we just pass a function by name or anonymously:
Alright, so now we have the exact same program in much fewer lines of code, its readable, and its very evident what its doing.
Now someone might say “that’s a neat trick, but when would I use it” — there are plenty of cases when you’d want to pass functions around like this. It gives you a lot more power to abstract your programs control flow in novel ways. Adapted from an example shown here, consider a class which handles files:
Yuck. The code is repetitious, but its performing operations on different classes and invoking different methods. How would you abstract away the duplicated code in the OO universe? In functional programing, it’s trivial:
Awesome.