2 min read

Categories

  • Programming

Tags

  • C++
  • Functional

I was procrastinating as always in my free time when I suddenly felt this big empty hole inside me about functional programming and C++. So I decided to write this blog post to delve deep into the topic. Of course I’m joking. I always wanted to write such a blog post. I just didn’t have the courage. Anyways let’s get into it.

So what is functional programming? Because I don’t want to make abrupt mistakes I’m going to use the help of our lord and savior Wikipedia. It says: “functional programming is a programming paradigm where programs are constructed by applying and composing functions”. Yes, whatever Wikipedia says. So with that out of our way I hope you now have a better idea about functional programming. If not you can always search on your own for more.

Alright so what was this blog about? Uhh C++? Functional Programming? How?

Enter The New ISO Standard

With Concepts in C++20 and all the other stuff we had before, we now have the tools to build a somewhat functional programming paradigm for ourselves in C++. But before that we may need to familiarize ourselves with a few things.

Map

It’s easy. It takes a group of things and applies a function on them, then produces a new group. Let me show you with good ol’ C++. See? It’s possible in C++ and understandable. Let’s run it in CompilerExplorer and see what it does.

Run it and you can see it simply returns a squared list of our vector. Well that’s map out of the way.

Fold

Fold is like map but instead of giving one group, it gives us only one element. It reduces lists into one thing. Here’s the example code in the C++:

By running it we see it multiplied all of our results into one single value of 120. Pretty simple huh? Well you might also ask what that 1 is. That’s the initial value. Change it and see how it changes everything.

Knock! Knock! Who’s there? Concepts!

I’m pretty sure you come across this situation in programming C++ templates where you wanted to make sure only certain kinds of arguments were passed into your functions. And if not, at least the compiler showed you proper error messages. Well concepts try to solve that. Also they are a good tool to do functional programming since we can enforce some certain things.

Okay let’s see them in action. Remember our last example? I’ll modify that. And then pass a vector of strings to it. Well it’ll look like this.

Appreciation

Thank you for reading the blog post. In the future I’ll post more in this blog. This post was just a short start. I hope you enjoyed your time.