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
 
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 :)

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
 
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
 
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
 
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
 
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
 
kroxis profile image
Vladislav Zhukov

Thank you very much!

Collapse
 
williams-37 profile image
Williams • Edited

Thanks for sharing this .. ~🙃

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
 
menokoog profile image
Lawrence "Menoko OG" Jefferson II

Thank you awesome read.

Collapse
 
siy profile image
Sergiy Yevtushenko

Mentioning Kotlin and omitting Java is strange at best.

Collapse
 
pingify profile image
Pingify

Nice

Collapse
 
kontactmaneesh profile image
kontactmaneesh

Nice

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
 
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.