DEV Community

Cover image for A Guide to Functional Programming

A Guide to Functional Programming

Dhanush on November 11, 2024

Functional programming has gained popularity due to its ability to provide efficient and scalable solutions. It's a declarative approach to program...
Collapse
 
dhanush9952 profile image
Dhanush

Follow my profile if you find my posts helpful.

Related posts:
1. Collection Interface - Quick Overview
2. Upcasting and Downcasting in Java: An Overview of Typecasting
3. Data Structures: Creating Custom Node Classes
4. Multithreading in Java: A Comprehensive Guide
5. Java program to find Nth fibonacci number
6. Interfaces and Abstract Classes in Java
7. Mastering Lambda Expressions in Java 8: A Comprehensive Guide

Follow me on X:

Collapse
 
leob profile image
leob

I love the idea of FP, but it just refuses to become mainstream - it stubbornly remains in the "niche" corner (apart from the odd snippets of filter/map/reduce code gaining popularity in JS) ...

To be honest I think there's a class of "difficult" problems where FP is great - it's just that the great majority of the code that we write in e.g. web development is too simple and too trivial to benefit from FP's power - i.e. in most cases we just don't need it ...

P.S. point 3 "Easy to read" - anyone who ever tried to read "deep" Haskell code might disagree ;-) ... FP can be super powerful, especially for complex problems, but I would hesitate to list "easy to read" as one of its advantages :)

P.S. you forgot to mention one of the most popular FP languages, which at some point was hailed as "the new Ruby" - Elixir !

Collapse
 
webbureaucrat profile image
webbureaucrat

I do think it's coming into the mainstream. I'm not sure Haskell per se has gotten bigger, but certainly languages like Java and C# are adopting a lot of functional thought whereas they had been entirely object oriented. People don't think of Rust as functional, but it has definitely adopted a lot of important ideas from functional programming like like using variants (enums) and restricting mutability. I think FP is generally winning but it's winning by taking over non-FP languages rather than widespread adoption of e. g. Elm and OCaml.

Collapse
 
siy profile image
Sergiy Yevtushenko

I think it's not FP is winning, but life finally prove that there is no "OO vs FP" but "OO+FP". All mainstream languages are migrating towards hybrid model (with notable exception of Go, which is stuck in OO+procedural programming era).

Thread Thread
 
leob profile image
leob

Right! Yes that's what you can clearly see happening ...

Collapse
 
leob profile image
leob

You're right that it's more about FP features creeping into non-FP languages, than pure FP languages gaining a lot of ground ...

I've studied Rust a bit, and actually it felt very much "FP" to me - more "FP" than "OO" ... it's not a pure FP language, but man does it almost feel like one ... the popularity of Rust could be the strongest case of "FP" gaining ground.

Thread Thread
 
siy profile image
Sergiy Yevtushenko

Perhaps this is because most older languages came from OO camp. Rust had no such legacy and just stripped out some unnecessary OO parts. Otherwise it's typical hybrid FP+OO language.

Thread Thread
 
leob profile image
leob

Rust doesn't even have "proper" inheritance - I think you can do inheritance if you REALLY want to, but they've made it very hard ... but yes, "hybrid FP+OO" you could say that - for me it felt very much FP, with OO being something like an afterthought!

Thread Thread
 
siy profile image
Sergiy Yevtushenko

"Proper" inheritance is barely necessary. Thrait inheritance is more than enough. I'm writing Java code in the same style - inherit interfaces but classes are final.
And no, OO in Rust is not an afterthought. Dyn traits is a pure OO thing.

Thread Thread
 
leob profile image
leob

Yeah traits are OO, so you're right that Rust is still a mix of FP and OO ... but the fact that they skipped "classical" inheritance is telling :)

Thread Thread
 
siy profile image
Sergiy Yevtushenko • Edited

Well, traits are type classes, which is an FP feature, but they also very similar to OO interfaces. Support for inheritance is purely an OO thing. In other words, FP and OO have many things in common for a long time and there is just no sensible reason to strictly separate them. Especially from a pragmatic point of view.

Collapse
 
dhanush9952 profile image
Dhanush

Dear @leob
Thank you for the thoughtful feedback on my post about functional programming. I really appreciate your perspective and insights.

You raise some excellent points about the challenges of functional programming becoming mainstream. I agree that it tends to remain in a more niche corner. The power of functional programming really shines when tackling more complex and mathematically oriented problems, as you mentioned.

I also appreciate you calling out my claim about "easy to read" as a potential advantage. You're absolutely right that highly abstract and complex functional code, especially in languages like Haskell, can be quite challenging to parse for many developers. I should have been more nuanced in my assessment there. I have installed Haskell last week and tried some tasks on my own.

And thank you for the suggestion to include Elixir as one of the popular functional programming languages.

Elixir

Elixir is a dynamic, functional language for building scalable and maintainable applications.

It's an excellent example of a language that has gained significant traction, especially in the realm of concurrent and distributed systems. I'll make sure to add it to the list in a future revision of the article.

Overall, I'm grateful for your technical feedback and willingness to engage critically with the content. It will really help me improve my understanding and articulation of the strengths, limitations, and nuances of functional programming.

Comments like yours are invaluable for helping me produce more well-rounded and accurate writing.

Thank you!

Collapse
 
siy profile image
Sergiy Yevtushenko

I think two main issues which prevent wide adoption of FP are terminology and focus on purity. In real life hybrid of OO and FP slowly spreads into mainstream.

Collapse
 
j3ronimo profile image
J3ronimo

True. I've seen Matlab code where tons of variables are passed into a function and then returned back. While that might be "pure" FP, it's the opposite of everything this article tries to sell you, like being easy, maintainable, scalabe, readable, efficient, and what not ...

Collapse
 
leob profile image
leob

Right ... but if FP isn't pure then it ain't FP ! :P

Thread Thread
 
siy profile image
Sergiy Yevtushenko

Perhaps. But I don't care because I prefer pragmatic approach. For purists I don't call this FP but ""functional style" :)

Collapse
 
krinara86 profile image
Krishna

I think it should remain niche. Because once they try to become mainstream slowly they lose their usefulness for the context they serve.

It should be upto the software engineer and architect to make choices on which programming languages go where instead of seeking a one stop shop solution.

Collapse
 
leob profile image
leob

Now I come to think about it - one of the best examples where "FP" has gained ground is the way React components are programmed nowadays, as "functional" components - no OO in sight, purely functional - the name useEffect (where you typically code your "side effects") is a dead giveaway!

Collapse
 
dscheglov profile image
Dmytro Shchehlov

FP is really great, and I think all developers should study it to some extent. However, the benefits of FP are discussable and may vary depending on the context.

  • Easy to debug — It depends on the language and IDE, but generally, FP code is more complicated to debug, especially when written in a point-free style. It’s better to consider testing. Writing unit tests for pure functions is truly a pleasure. 😊

  • Lazy evaluation — This is not specific to FP. For instance, the Command Pattern can be used to support lazy computations.

  • Supports parallel programming — Immutability and function purity were designed specifically to make parallel programming possible. However, this is not unique to FP.

  • Easy to read — Not necessarily. Even Haskell uses do-notation to avoid chaining "bind" calls and make the code more readable. Do-notation is syntactic sugar that mimics an imperative style.

  • Efficient — It depends... 😊 Immutability isn’t free. Brute forcing it requires more memory and CPU to copy objects and lists. To do it efficiently adds additional complexity, which is also less effective than mutation.

Collapse
 
tr00per profile image
Artur Czajka

Recursion is not expensive to use if the language supports tail recursion optimization. The compiler then effectively transforms recursion into a plain iteration. Haskell supports this, as do other FP-centric languages (check out the Wikipedia entry).
Terminology is an entry barrier, but once you get a grip of it, it tends to be used consistently across different languages. With a few exceptions, of course :P

On the other hand, I would disagree with most of the mentioned "pros" :P

  • Easy to debug? Only once you're familiar with the language and the terminology ;)
  • Lazy evaluation? Not necessary for an FP language, and even in Haskell you sometimes want to make stuff explicitly eager, and laziness goes directly against ease of debugging, as you don't know right away when stuff is called.
  • Nice parallelization? Yes, actually, pure functions and immutable data especially are great for parallelization :)
  • Easy to read? I assure you, you can create a Big Ball of Mud in an FP language with same efficiency, as in an OOP language :D
  • Efficiency - I don't get your point here, as any useful program as a whole needs to communicate with the outside world. I do agree, that making pure functions helps with modularization.

What I'd add as a pro:
Using declarative style, sum types & higher-order functions forces you to think about the problems you're solving in a different way, adding to your programming toolbox. For that reason I recommend trying an FP language to anyone (Haskell, Scala or F# in particular) for some toy exercises (I recommend Exercism, but there are numerous platforms) :D

Collapse
 
dhanush9952 profile image
Dhanush

Dear @tr00per
Thanks for the thoughtful response. I appreciate your insights on functional programming.

I completely agree with all your points, and I think your enthusiasm for Haskell is infectious. As a fan of functional programming, it's great to see someone who is so passionate about the subject. Your insights on the benefits of FP, from parallelization to declarative style, are spot on. Thanks for sharing your thoughts and for helping to spread the love for Haskell and FP in general!

Overall, I think your response was well-reasoned and thought-provoking. It's great to see different perspectives on programming paradigms. I think it's always beneficial to learn from others and expand our programming skills.

Thanks again for your response.

Collapse
 
danp profile image
danp

This is amazing that one оf the more popular languages is omitted here, which very well supports all these aspects of functional programming, and supports strict typing by the way - so is much better than JS, the good old PHP.

Collapse
 
dhanush9952 profile image
Dhanush • Edited

Dear @danp

I wanted to reach out and apologize for not including PHP in my original list of functional programming languages. I know PHP is a popular language that supports many functional programming concepts, and I appreciate you bringing it to my attention.

PHP is a multi-paradigm language that supports functional programming concepts. ✅

While it's not a purely functional language, PHP provides several features that allow developers to write functional code.

PHP supports lambda functions, which are small, anonymous functions that can be defined inline.

Here's an example:

$numbers = [1, 2, 3, 4, 5];
$doubledNumbers = array_map(function($x) { return $x * 2; }, $numbers);

print_r($doubledNumbers); // Output: Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 8 [4] => 10 )
Enter fullscreen mode Exit fullscreen mode

PHP supports closures, which are functions that have access to their own scope and can be used as higher-order functions.

function createMultiplier($multiplier) {
  return function($x) use ($multiplier) {
    return $x * $multiplier;
  };
}

$double = createMultiplier(2);
$triple = createMultiplier(3);

echo $double(5); // Output: 10
echo $triple(5); // Output: 15
Enter fullscreen mode Exit fullscreen mode

As explained before, there are still many other programming languages that support functional programming concepts.

We cannot mention every one of those languages. These languages listed here are quite popular one. There is no targeted attack or discrimination on any languages done here.

These are just a POV.

You can write your own post mentioning PHP on first place. No offence. ❌

Thank you for mentioning PHP.

PHP is the most widely used server-side programming language on the web. In fact, PHP is used in 79.2% of all websites, making it one of the most popular languages among programmers and web developers.

Collapse
 
entre0sy1s profile image
Aprendiendo Entre Ceros y Unos

Excellent article! First of all, thank you for sharing your knowledge. For people like me who want to start learning FP, these publications are invaluable. However, I am a newbie in this field and I wonder, where are the if, switch, for or while statements? Because what I understand so far is that under this paradigm I should try to use functions. So, should I create recursive functions, for example, instead of using an if, switch, for or while statement? Or in what moments or context should I use if, switch, for or while statements? :)

Collapse
 
dhanush9952 profile image
Dhanush

Dear @entre0sy1s
Thank you so much for your kind words about the article! I'm thrilled to hear that it's been helpful to you as you start learning about functional programming. Your question is a great one, and I'm happy to help clarify things for you. 🙂

I'll make sure to write a follow-up response to address your question about using if, switch, for, and while statements in functional programming.

Thanks for your feedback!

Collapse
 
pengeszikra profile image
Peter Vivo • Edited

I also like FP, most of the time it is help a lot with my work. But in real life legacy code where someone intensive use ramda - js FP library - that cause code much harder to read. So many cases this solution is give extra abstraction to your code.

I also big fan of pipeline operator, but saddly cant implement into JS ( proposal one can be used but it need to use babel for that )

Collapse
 
dhanush9952 profile image
Dhanush

Dear @pengeszikra
I completely agree with you that while functional programming can be incredibly powerful and helpful, it can also be misused or overused, leading to code that's harder to read and understand.

Ramda is a great library, but like any tool, it can be used in ways that make the code more abstract and less readable.

Ramda

I also share your enthusiasm for the pipeline operator, and I'm looking forward to seeing it become a standard feature in JavaScript. The proposal is promising, but having to use Babel to implement it can be a barrier for some projects.

Hopefully, it will become a standard feature in JavaScript soon, making it easier to write more readable and composable code. Thanks for sharing your thoughts and experiences with FP in real-world projects!

Collapse
 
rohitkhokhar profile image
Rohit Khokhar

Such a well-crafted post! You’ve covered all the key points and presented them in an interesting and accessible way. It’s clear that you put a lot of thought into this, and I’m grateful for the valuable knowledge you’ve shared.

Collapse
 
dhanush9952 profile image
Dhanush

@rohitkhokhar
Thank you so much for your kind words!

I'm thrilled to hear that you found the post informative and engaging. I'm glad that I could help share my knowledge with you in a way that was easy to understand. Your feedback is greatly appreciated, and it motivates me to continue creating high-quality content.

Thank you again for taking the time to read and respond!

Collapse
 
siy profile image
Sergiy Yevtushenko

Mentioning Kotlin and omitting Java is strange at best.

Collapse
 
dhanush9952 profile image
Dhanush

ok😃

Collapse
 
williams-37 profile image
Williams • Edited

Thanks for sharing this .. ~🙃

Collapse
 
beandnam profile image
beandnam

i'm not sure for Go is functional programming?

Collapse
 
dhanush9952 profile image
Dhanush • Edited

Yes @beandnam ,

Go is a multi-paradigm language, but it's not typically considered a functional programming language. While it does have some functional programming features, such as closures and higher-order functions, its design and syntax are more focused on concurrency and simplicity. Go does have some functional programming elements, and it's possible to write functional-style code in Go, but it's not a language that is typically associated with the functional programming paradigm.

Collapse
 
kroxis profile image
Vladislav Zhukov

Thank you very much!

Collapse
 
menokoog profile image
Lawrence "Menoko OG" Jefferson II

Thank you awesome read.

Collapse
 
chandragie profile image
chandragie

First class and HOF sounds similar 🤷🏽

Collapse
 
kontactmaneesh profile image
kontactmaneesh

Nice

Collapse
 
pingify profile image
Pingify

Nice

Collapse
 
husseinkizz profile image
Hussein Kizz

Have you heard of ADTs?, just asking how do they fit into FP?

Collapse
 
davidi99 profile image
David Intersimone

Seems like every programming language can be used for functional programming. Just follow the patterns.

Collapse
 
dhanush9952 profile image
Dhanush

Thank you for your support😃

Follow @dhanush9952