CppCast - Functional Programming in C++
Episode Date: June 27, 2019Rob and Jason are joined by Ivan Čukić to discuss his book on Functional Programming with C++. Ivan Čukić is the author of "Functional Programming in C++" published by Manning. He is one o...f the core developers of KDE, the largest free/libre open source C++ project. He is also teaching modern C++ techniques and functional programming at the Faculty of Mathematics in Belgrade and has been using C++ for more than 20 years. He has been researching functional programming in C++ before and during his PhD studies, and uses the techniques in real-world projects. News Rust and C++ Cardiff State of Developer Ecosystem 2019 Voting on the talks for Meeting C++ 2019 Pre-Cologne Mailing Ivan Čukić @ivan_cukic Links Functional Programming in C++ p0798R3 Monadic operations for std::optional p0323R8 std::expected Immer library Ranges for distributed and asynchronous systems - Ivan Čukić - ACCU 2019 Functional reactive programming in C++ - Ivan Čukić - Meeting C++ 2016 Sponsors PVS-Studio Facebook PVS-Studio Telegram PVS-Studio Twitter JetBrains Hosts @robwirving @lefticus
Transcript
Discussion (0)
Episode 204 of CppCast with guest Ivan Chuchik, recorded June 27th, 2019.
Sponsor of this episode of CppCast is the PVS Studio team.
The team promotes regular usage of static code analysis and the PVS Studio static analysis tool.
And by JetBrains, maker of intelligent development tools to simplify your challenging tasks and automate the routine ones.
JetBrains is offering a 25% discount for an individual license on the C++ tool of your choice.
CLion, ReSharper, C++, or AppCode.
Use the coupon code JetBrains for a CPP cast during checkout at JetBrains.com. In this episode, we discuss papers going into the Cologne meeting.
Then we talk to book author, Ivan Kuchik.
Ivan tells us about functional programming with C++ developers.
I'm your host, Rob Bervink, joined by my co-host, Jason Turner.
Jason, how's it going today?
I'm doing all right, Rob. How are you doing?
I'm doing fine. how are the Netherlands? Yeah I am traveling right now and last year when I was here it was record-breaking
heat and then I was in Israel for Core C++ which was record-breaking heat for May and now I am in
the middle of a record-breaking heat wave again here in the Netherlands.
It's very exciting.
Yeah, you're just getting really lucky there with that travel, I guess.
Yeah, the most exciting part of it is no one in the Netherlands really has air conditioning
because they theoretically don't need it except for when I am visiting.
The heat waves are pretty rare over over there i guess yeah yeah to put it in comparison
like it's pretty rare for it to get over about 82 degrees or something like that wow okay yeah
well hopefully you come home soon so you can uh relieve the rest of the people over there in the
netherlands yes i i apologize for our our d here. Yeah. Okay.
Well, that's sort of like a piece of feedback.
This week, I got a Twitter message from Chris Tao saying,
Hi, guys.
Great job.
Love your podcast.
Could you mention on air that Cardiff Wales has their own first meetup for C++ Rust developers?
They're looking for enthusiasts to improve our skills
by sharing knowledge and having fun.
And he sent me a link for the Rust and C++ Cardiff Wales meetup.
So I will share that in the show notes.
Yeah, and it looks like they're getting some interest.
They already have 78 members signed up on meetup.
And I think they already had one event um i think a week ago
but they i'm sure we'll have uh more upcoming and uh yeah if you're anywhere near uh cardiff wales
go check out this new c++ and rust meetup yeah definitely i wonder how they're going to handle
topics i haven't heard of like combined language meetups like this.
Like do they take turns?
Do they try to talk about both Rust and C++ during each meetup?
I don't know.
Maybe they have like a battle or something at each meetup to see which one is the better language on a certain topic or something.
It sounds like it'd be pretty combative.
Yeah.
Find that out every month.
Yeah.
Yeah.
Okay.
Well, we'd love to hear your thoughts about the show.
You can always reach out to us on Facebook, Twitter,
or email us at feedback at cpcast.com.
And don't forget to leave us a review on iTunes
or subscribe on YouTube.
Joining us today is Ivan Truchik.
He is the author of Functional Programming in C++,
published by Manning.
He's one of the core developers of KDE, the largest free Libre open source C++ project.
And he's also teaching modern C++ techniques and functional programming at the Faculty of Mathematics in Belgrade,
and has been using C++ for more than 20 years.
He's been researching functional programming in C++ before and during his PhD studies and uses the technique in real-world projects.
Yvon, welcome to the show.
Thank you.
Thank you for inviting me.
I'm curious, like, how long have you been with the KDE project?
For more than 10 years now.
More than 10 years.
Wow.
Now, I guess for history for our listeners, I guess, would you mind explaining what KDE is and how long it has been around?
So to be honest, I think it has been around for, I don't know, 25 years or something like that.
The idea was in the beginning to create a graphical environment for Unix.
And obviously it grew up when Linux became popular, etc.
And now it's not only the desktop environment. Now we have office suites, we have artist painting applications and everything
else. In essence, it's just a huge, huge community of C++ and Qt developers working on beautiful
things. Yeah, so I guess that's the other relevant bit of information is KDE uses Qt for all
of its GUI aspects, right?
Yeah, yeah.
In essence, for most of it, obviously, we have some, we also have frameworks.
So the libraries for extending, for example, Qt library is kind of comprehensive, but they still lack stuff like, I don't know, zip or archival support and stuff.
So we do provide libraries for any Qt application or any C++ application to use to extend,
not to reimplement all the functionalities exactly like supporting zipss, TARs, etc.
Very cool.
This was a little bit of an awful explanation
because I just mentioned one of the frameworks.
But for people who are interested,
just go to Google and search for KDE frameworks
and you'll get a few dozen libraries
that you can use in your regular projects.
Very cool.
Okay, well, Ivan, we have a couple news articles to discuss.
Feel free to comment on any of these,
and then we'll start talking more about functional programming in your book, okay?
Okay, of course.
So this first one is the JetBrains State of the Developer Ecosystem for C++ 2019.
And these are just the results from a survey they sent out and compiled
together. And yeah, I think we've gone over this in past years. There's definitely some good trends
to see here, like over 60% of listeners responded that they're using C++ 11. Very, very few
responders are still using C++ 98 or 03, which is great.
There's only like 20% are still using the older versions.
Although, to be honest, for people who use the old versions, I don't expect them to have
seen the questionnaire.
Yeah, yeah.
I'm sure there's a bit of a self-selection bias with the people who are responding to this.
That's a good point.
Any other results that you guys wanted to highlight?
One of the other interesting things was they're continuing to see CMake take over the other build systems.
They said it beat out Visual Studio last year and since gained another 5% on top of Visual Studio.
I thought that was interesting.
Yeah, love it or hate it, it's our standard at the moment, really.
Yeah.
Even Qt is going to switch to CMake in Qt 6.
Is that right?
Does that mean that they are dropping Qmake altogether?
So a couple of years ago,
they started developing a new build system called QBS.
Oh, right.
And they kind of abandoned it in favor of CMake for Qt 6.
I think that QMake is still going to be supported
because a lot of projects currently use it.
But Qt itself will be built with CMake.
Wow, that's pretty crazy.
Yeah.
It's been a big change over the last 10 years or so,
watching all this kind of
thing happen okay and then uh the next thing we have is voting on the talks for meeting c++ 2019
and jason do you recall if they did this before where they allow just any attendee or just any
member of the meeting c++ community to vote on, which talks they want to see at the conference.
I don't recall seeing this last year.
I believe it was only current or past ticket holders on previous years.
Okay.
And speakers and speakers.
Right.
Yeah.
Okay.
So now it's opened up to just anyone who has an account with meeting C plus
plus who wants to go on and vote.
I'm not sure.
I,
I,
it is cause I, I created an account when I saw this article and then++ who wants to go on and vote i'm not sure i i it is because i i created
an account when i saw this article and i was able to go in and look at some of the session
descriptions and vote yeah okay okay so did you go and vote for random talks uh i flipped through a
couple of them i didn't go through every single talk i will say it'd be nice if you could get
kind of an overall list of what all the sessions are you kind of need to just go through each one and assign a rating um so i think the ui for uh going through
it could be a little bit more streamlined yeah he says the only requirement is that you have a
meeting c++ account or have purchased a ticket for this year's conference yeah okay yeah so
neat idea though to let every let every single possible attendee
go and vote for the talks they want to see.
That is interesting.
And then last thing we have
is that the ISO C++ pre-clone mailing
has gone out.
I didn't see what the number of talks was.
I'm not sure how it compared to the last two
where they were kind of setting record numbers, but it seems to be a pretty sizable mailing not papers yeah
yeah do you have any uh involvement with the iso committee even uh not really i'm only a member of
the sg20 education study group oh okay in essence a few times I wanted to write a paper on something,
and then I realized it's a little bit too legalese for me.
Yeah.
There are definitely a few things that stand out to me on here.
Sure, go ahead.
The invitation for the 2020 Prague meeting will be as one of the top
papers. So 2020, the first meeting of 2020 is in Prague out of AST. So that's interesting.
And I noticed one of the top things I noticed was a paper from Ben Dean here, because apparently
all of the recent papers to make sure that standard algorithms were constexper
mixed missed the algorithms that are actually in the numeric header oh that's interesting yes
so that's like oops because that's you know accumulate one of the more common ones to use
one of the things i noticed was that the 2D graphics
proposal seems to be back.
There's an update
to that paper
with Guy Davidson, Herb Sutter,
Michael McLaughlin.
I'm surprised to see that one coming
back, but I guess they never
fully let it die because they were trying to get it through the
British standards body.
They invested a lot of time. Yeah, body. They invested a lot of time.
Yeah, and they did invest a lot of time.
Yeah.
Any other specific papers either of you
wanted to call out? I would say
STD expected.
We should finally get something
that some other
languages I'm not going to mention
have had a long, long time ago.
I also saw... Oh, go ahead, Jason.
No, go ahead, Rob.
I'll come back to you in a second.
I was just going to say, I also saw this paper
saying to boldly suggest
an overall plan for C++23
to actually
upfront commit to
what types of features
they want to be able to bring to the table when c++
23 is ready to be uh finalized so i thought that was interesting to uh try to get up front and uh
get agreement on what to focus on for the kind of next cycle i thought that seemed like a good idea
who is on that paper uh i'm not gonna pronounce pronounce the name, but Ville Voutelainen.
Okay, Ville, okay, yeah.
Yeah, and he's suggesting that library support for coroutines,
executors, and networking should be the most important feature deliverables
for C++23, and reflection and pattern matching should either make progress
or get into C++23 as well.
All right, cool.
It seems like a good list of things to try to get in.
There's one here, no discard for constructors.
So being able to mark types or mark constructors is no discard.
Yeah, that one struck me as interesting. I've had a lot of students that when they try to do RAII,
they just create a temporary and it just gets destroyed at the semicolon.
So this could be quite useful.
I guess that might stop people that do weird hacks,
like using the comma operator to create a mutex
for just the lifetime of an assignment operation.
Have you seen that one?
Not in the real life.
I think I know people who have.
Yeah, I know people who have done it in real life.
I think not that I would recommend it.
Okay, well, moving on from this,
let's start talking about functional programming.
And for our listeners,
should we maybe start with an overview
of what exactly functional programming is
and how it differs from object-oriented programming
that might be a little bit more familiar?
Oh, I have to say that I had that question.
In essence, that was one of the most difficult things to write in the book
because the publisher wanted me to make a clear distinction
and show how FP is much better than OLP.
For me, both of them are a set of techniques,
and you can mix and match those techniques.
With functional programming, the idea is that you're not creating abstractions over data, like in OOP, but mostly abstractions over functions.
So, for example, STD algorithms like STD accumulates and stuff, that can be called functional programming in, let's say, C++ style.
Okay. and stuff that can be called functional programming in let's say c++ style okay okay so just a set of practices that that rely on abstractions to create to make your code a little bit shorter and a
little bit safer that makes sense so it's not better than object-oriented programming or anything
like that from your in your opinion from what you saying, it's another tool in our tool bag. Yeah. Obviously, again, with OOP,
you have good OOP and bad OOP.
I would say that functional programming is better than bad OOP,
and it can be mixed and matched with good OOP.
So bad functional programming is...
No. Yes. okay, got it.
So is C++ an effective language with functional programming?
Because I know there are certain languages that are kind of made to be functional programming languages,
like Haskell is one that comes to mind.
Yeah, I didn't want to mention the name of Haskell.
But okay.
In essence, I really love Haskell,
but the thing that I do mind is that
I don't want the language to put, let's say, chains on me
and force me to do something in a certain way.
In C++, we can do whatever we want,
and we can even do functional programming.
In Haskell, if you want to make something,
because it's a pure language,
if you want to change state,
you need to go through all the hoops
to simulate mutable state.
And obviously people claim that
it's still much more easy to reason about
because it's still pure.
But I have a beautiful counter argument
there was a paper called lambda the ultimate imperative where everything was implemented
just in c style in haskell just imagine a c program written in haskell syntax it's completely
unreadable both of them so i wouldn't say that purity by itself and enforcement in the language is a good thing.
With C++, the great thing is that we can create the, let's say, not the same,
but similar abstractions like in Haskell and write, let's say,
more brief code and safer
code than normal C++ is.
So I kind of want to take just a little bit of a step back, maybe,
and ask, like, why were you inspired to write this
book in the first place? Okay, that's a fun
story, at least for me.
Okay.
All the conferences that I went to, so meeting C++
and stuff.
I usually gave talks about monads and other functional things.
And after that, usually you have a beer party or something like that,
and you get a group of people that like functional programming.
And the conclusion was always that we would all love to have a book on functional programming in C++
so that we could learn something more.
And obviously nobody wanted to write the book.
And at some point, me neither.
And at some point Manning approached me to write it and I said,
I really don't want to.
But then I realized, okay, if everybody says I don't want to,
we are never going to get a function programming book in C++.
So in the end, I said kind of, okay.
I had absolutely no idea what I'm doing,
and I had no idea how much time it will take.
Writing books is not really an easy job.
I have heard it takes a considerable amount of effort, in fact.
Yeah. So I've heard that when you do a self-publishing then it's a little bit lighter on you but when you have a professional publishing company
behind for each of the chapters you have at least three revisions, three dozen
different people go through your wording and everything else and then try to fix it to
fit the style of the publisher, etc. So in essence, if you were just writing chapters, chapters,
chapters like blog posts, it would be much, much more simple. But the fact that you need to
rewind, rewind and revise everything, it was a little bit painful.
So how much effort can you estimate how long it took for people who are maybe considering writing a book with a publisher?
So they told me that, let's say, normal authors write one chapter per month.
And for me, it was completely unrealistic.
In essence, it would mean that my book should have been written in a year.
It was in kind of two years.
Three years.
Okay, so you wrote one chapter every three months, basically, is what you're saying.
Two years, not three.
Oh, okay.
Let's say one chapter every two months.
Although, again, it's not a problem that it took two months.
Each chapter took, let's say, one and a half, and all the revisions took the rest of the time.
Right.
Okay.
So, ultimately, you were approached by Manning, you went ahead and went with it, and has it gone well?
Are you glad that you went through the effort now?
Yeah, of course. So even if it took a lot of time and some parts were painful,
but I have really learned a lot on how to write.
Manning does have some strange guidelines with writing, but it was amazing how...
So I had a couple of developmental editors or something like that. And they really taught me how to present things that readers really love
when you say the same thing in three different ways.
One with a picture and two different ways to explain something in words.
And obviously they forced me to do the same thing through the whole book.
And I'm really grateful for for let's say those
people that helped me write it it was it's an amazing experience it doesn't really pay off that
well but as an experience it's something that they recommend well the book has been very well
received too i know i've seen lots of good good blog posts reviewing the book and actually met a listener in person who highly
recommended it and actually asked me to try to get you on the show several months back.
So has that been the case? You've gotten lots of good feedback?
I didn't expect it to
let's say be a popular C++ book because nobody wants to read
functional programming in C++. because nobody wants to read Functional Programming C++, but
people who have read it
they mostly had positive
impressions
and often at
all the conferences people approach me
to sign, to at least say
hello, etc.
With that in mind
I really don't care whether
the book brings me any money or anything else.
For me, the main point of the book is to give something to the C++ community back,
because I have learned a lot by listening to people at conferences and reading other people's books.
I am one of those listeners, I guess. Am I a listener of C++?
Not technically, no.
No.
Not in a long time.
I am one of those who has purchased your book, and I have gotten started with it.
I've read the introduction, and I'm excited to dig in.
But I find myself mostly wanting to read on an airplane or something because I do a lot of travel.
But I want to have my laptop available to be able to practice the stuff that you're talking about
and I just, you know, like
would you recommend that I do have my laptop
with a compiler available while reading it
or do you think it's something that you can just kind of casually read?
Well, if you want to read it just once
then I would say bring your laptop with you
otherwise the main point in that is that
the idea is behind all the functional stuff.
Now, I don't expect you to actually need a compiler
for you to read the code and know what it is doing,
because I'm not doing anything that insane.
But let's say for an average listener,
I would say it's useful to have a compiler nearby
Okay, thank you
I want to interrupt the discussion for just a moment
to bring you a word from our sponsors
PVS Studio is a tool for detecting bugs and security weaknesses
in the source code of programs written in C, C++, C Sharp and Java
It works under 64-bit systems in Windows, Linux and macOS environments
and can analyze source code intended for 32-bit, 64-bit, and embedded ARM platforms.
The PVS Studio team writes a large number of articles on the analysis of well-known open-source projects.
These articles can be a great source of inspiration to improve your programming practices.
By studying the error patterns, you can improve your company's coding standards, as well as adopt good programming practices which protect from typical errors. For example, you can stop being greedy on
parentheses when writing complex expressions involving ternary operators. Subscribe to
Facebook, Telegram, or Twitter to be informed about all publications by the PVS Studio team.
Links are given in the podcast show notes for this episode.
Could we maybe dig into some of the concepts of functional programming that you go
over in the book? Like where would be a good place to start? So the first part that I tried
to stress out and a couple of people complained about it is that for me functional programming is
primarily about high-order functions. So functions that can accept other functions as arguments or
functions that return new functions as the result. And I tried to convey that STL algorithms and a
lot of STL is actually, even if it's a little bit strange functional, it is functional. All the
algorithms are high-order functions, etc. And obviously, during the review process, I had quite a few complaints that I'm not talking about functional programming, I'm talking about STL.
But that's the first step that I would say people need to understand.
Functional programming is not something that is completely strange and foreign.
It's something that they have been at least to some extent used in normal C++.
So I would say that's the first step,
using higher-order functions to do fun things like algorithms.
Okay.
And after that, obviously, you have quite a few crazy concepts
like monads, unions, and stuff.
Okay.
You did it.
You mentioned... Did the M word. Sorry. Yeah, I don't think... You did it. You mentioned...
You said the M word. I'm sorry.
Go ahead and finish your sentence, though, please.
I just wanted to say that unions are no longer that foreign.
Although, neither are monads.
We have a couple of them in the standard nowadays.
Okay, now you've said it twice.
So, what you have to do now is...
You have to succinctly describe to us what a monad is.
Is that a requirement of the show?
Okay, how about we do this differently?
You said we have a couple in the standard and they're no longer foreign to us.
Tell us what in the standard is a monad, perhaps.
So, for example,
std optional.
Although we are kind of
currently missing some APIs for it to
be a proper monad, and thanks
to Simon, we should be getting that
in, I think, 20 or 23.
I haven't really followed.
In essence,
if you want to have a function that returns
an std optional,
what would be the reason for returning optional instead of a proper value?
That's a question for you.
What would be the purpose?
You know, honestly, I really do not like interfaces that return optionals.
But I would say if you were to return an optional, it's because the value may or may not be available, I guess.
Like perhaps if you were doing a lookup in a map.
For example, you can either throw an exception,
or you can somehow report an error, etc.
And one of the ways to report an error is by just saying,
I can return a value or I can return nothing.
And, for example, when you get that optional,
it's sometimes a little bit tedious to deal with optional values because usually when you deal with them
it's like with pointers. If this is not a null opt then do something with the
values. So the first step with optionals is to try to think of them like ranges
or collections or something else. We have std transform, and std transform gets a collection of values
and returns a collection of transformed values.
Conceptually, not literally, right?
And the same thing can be applied to an optional.
If, for example, you said we have a map,
and just imagine the map is mapping login users to the user object that has a name
and surname etc. So your function returns optional of user type. And the question is how then you can
just say okay I don't care about the whole type I just care about the person's name. You can just
say transform the optional object and transform it to extract
the name instead of doing all the dense with ifs and dense, etc. Okay. Okay. This is a little bit
difficult to explain audio only, but I'll try. So you can do the transformations and you can,
for example, after when you transform, you're going to get std optional of string because you extracted the name.
But if the person didn't exist, then you couldn't have extracted the name.
Fine?
Okay.
Next transformation can be convert string to uppercase.
And again, you can chain the transformations on the optional object and you will just get the transformed,
well, again, optional of the transformed value.
And until this point, this is not yet a monad.
This is something that's called a functor,
and I'm trying hard to convince all the C++ people
not to use functor for function objects because of this.
Anything that has a transform is a functor.
And then the next step is what if all the transformation functions that you use to transform the optional don't actually
return a proper value, but they themselves return an optional. Okay. So for example,
just imagine that the function that converts the string to uppercase can sometimes fail and sometimes returns nothing.
If you try to use normal transform on an optional, you would just get optional of optional of something,
instead of just an optional.
And if you chain 10 of those functions, you will get optional of optional of optional of optional of string,
which is kind of useless.
Right, you're no better off. You're not, you're worse off in some sense.
Yeah, it's much worse.
And the main point of monads is that they don't do just transformation, but remove one
of the nesting from the optional.
So if you have, let's say, 10 of these partial functions that return optional values, you
can compose them just like normal functions, and in the end you're going
just to get an optional
of a value and not optional of optional
of optional, etc.
Now the problem with monads
is that...
I was just going to say that doesn't sound
too bad, and you're like, now the problem.
No, no, no. So the point
is that it's not too bad.
The problem is that all the people that try to investigate monads
first encounter Haskell,
and the input-output monad, because Haskell doesn't support state,
they needed to use monads to simulate input and output.
And most of the people who encounter monads first go to that,
and then everything is completely
let's... I'm trying
to find a word that is
that I should say
while being recorded.
Tainted by? Colored by?
No, no.
I wanted to say something that is a little
bit rude, but...
Oh, okay. Sorry. Just messed up?
Yeah. Messed up is a nice word so you just get
confused by all the stuff and monads are quite a simple concept just if you start thinking about
the removing the nesting after transformation then it makes sense for optionals for expectants
for std future etc okay even for ranges you started to say something, and I want to make sure if I heard you.
We think of transform over a container,
and I know there have been people that are like,
well, we should treat optional as a container of zero to one things.
And I think I saw a proposal even to extend begin and end and size and the free functions
to work on optionals and that kind of thing.
So we can truly treat them like containers and use them with the algorithms.
Is that like in the direction you would head personally or not?
Or am I misunderstanding something?
Yeah, I've quite a few times I've implemented
begin and end for optionals.
If nothing else, just imagine
you know the range syntax
with pipes and all the beauty of
ranges. And just imagine
on the left-hand side you just replaced the
vector of x's with an optional
without changing any syntax
whatsoever. If optional was a
proper collection, it would be possible.
And that's one of the coolest things about abstractions,
is that they allow you to use the completely same code
without any changes for completely different things.
Just imagine replacing, I don't know, ranges with reactive streams.
It could be the same syntax,
just with the completely different semantics
that you're processing an event stream
instead of processing a collection.
Okay.
Now, as someone,
I personally don't have any problem with exceptions at all,
which I know puts me in a rare place these days.
But if an error occurs,
you get an exception, you catch it, you have a description of what the
error was. So like the dot at interface for map, not that I use it all the time, but, you know,
being able to catch instead of, you know, having to go through a bunch of other steps. And what I
am a little lost on is with this optional monadic kind of interface. well by the way i did find that paper
simon brand it's p0798r3 was the last version of it from a monadic operations for optional
and you're talking about a transform of get a person's name get the first name do a capitalization
of it and you said you know like any one of those steps could potentially fail, so they could all potentially return optionals. Well, if the fifth out of nine steps is the one that fails,
how do I know that it was the fifth step that failed? That's an excellent question. So optional
just deals with whether the value exists or not. If you want to have the information about the reason why the value doesn't exist then you should use std expected from p0323r8.
So expected is kind of like an optional but instead of being a value or nothing
it's a value or an error. If you have the functions that can fail each of those
will return a value or an explanation why it failed.
And obviously, when you have the composition, as soon as any of them return an error,
you just immediately jump out just like you would with a normal exception. You just immediately
return the error as a result. The reason why I think that this is a little bit better than exceptions is, for example, in distributed systems,
when you have a border between two processes, you can't really transfer an exception through that.
If an exception occurs in one of them, you would need to have a really, really beautiful logic to
handle that exception and somehow propagate it. If errors are just normal values, you can just serialize the value and pass it on
using the same mechanism that you pass normal values through.
Okay, I accept that, yeah. Okay, so we've talked
a lot about monads. What are some of the other kind of core concepts
that we should really go over for a review of functional programming?
One of the other things that I talked a lot
and try to emphasize
that kind of belongs to functional programming,
but it's really beautiful with C++
are the unions or std variant.
So we have, I've seen recently a blog post,
somebody implemented a game with std variant.
I forgot whose blog post it was blog i think we talked about that
last week the spaceship yes we did yeah yeah maybe so unions are some one thing that is really really
used a lot in uh in functional languages and in c++ it let's say it gives more power to RII than normal classes would. Just imagine the following
my usual example is if you have if you want to write a program that connects to a web server
and fetches a web page and counts the number of words in the in a web page. Before you start
counting before you connect do you need a socket to that web page? Obviously not. Before you start counting, before you connect, do you need
a socket to that web page? Obviously not. So you could just have one state that
doesn't essentially remember anything apart from the URL to which you need to
connect. Then the next state in the variant could be the state that deals
with counting. So it needs to have a socket and it needs to have an int
that remembers how many words we have counted so far.
And the last state would be just the result,
so constant of how many words we counted.
The benefit of this compared to a normal class
that you just have count, socket, etc.
is that as soon as you switch from one state to another,
the destructor of the previous state is called,
so the socket is automatically closed,
and all the resources that you used in the previous state are automatically closed.
And you don't need to do that manually like most people do
when you just create classes and not variants.
Okay.
I hope I got the point through.
I'm not sure.
In essence, the point in variant is that
it can hold a value of a certain type,
of several certain types, right?
Yes.
Just one.
And if, for example, you have a variant
of string and something else,
as soon as you store something else
in the variant, the destructor of string
is called. Right. So it frees up all the resources else, as soon as you store something else in the variant, the destructor of string is
called.
So it frees up all the resources that if you designed it in class, string, and other type,
you would need to free, let's say, to clear up the string manually.
Then you decide, okay, I no longer need the value.
And with variants, it just automatically.
Okay.
I think it need the value. And with variants, it jots automatically. Okay. I think I've sunk in.
So in the spaceship game that we talked about last week,
his main point was with, or the author's main point there,
I'm not sure who it was, was that we have, with the variant,
you can encapsulate the rest of the state information
with each state type that's in the variant.
And you're pointing out not only because it carries information, but we can take advantage
of the variant to do our RAII resource management for us automatically, as well as a transition
between states.
Yeah.
Is that right?
Yeah.
Yeah.
Okay.
I probably just said the exact same thing that you did, but I clicked.
Okay. I probably just said the exact same thing that you did, but I clicked. Okay.
So are there any particular libraries or anything you would recommend for C++ developers who want to get into functional programming?
So the first one that I would always recommend is obviously ranges or std ranges for C++20. I would recommend Vicente's...
Sorry, not Vicente.
My brain is just frozen.
I don't know why I said Vicente,
but I'm looking at his proposal of std expected.
So there is a library by Juan Pedro Bolivar, I think.
Oh, yeah, he's done a bunch of great talks, yeah.
Yeah, he has an amazing library Juan Pedro Bolivar, I think. Oh, yeah. He's done a bunch of great talks, yeah. Yeah.
He has an amazing library that implements immutable collections,
really efficient ones that, let's say,
are comparable to the best data structures in pure functional languages.
So if you want to write pure code in C++,
you can check out his library.
It's called Imer, I-M-E-R.
And you have a really amazing implementation of a vector that is kind of copy and write,
but with persistent, all the previous values are still stored if somebody references them, etc.
So it's an amazing library.
Apart from that, I would say
Simon's optional and expected
implementations.
And I think that's most of it.
Simon Brand.
Excellent, thank you.
And are there any
particular types of application
that you think are better suited
for functional programming or a combination
of functional programming and OO?
So I would say that any application can benefit from some functional concepts.
People usually go for the low-hanging fruit of saying
when you have multi-threading, then purity is God and everything else.
But I really don't care about that stuff.
I just like writing
short code. I like
having less to write, and
functional programming is indispensable
for it. I don't know, I don't
care how much boilerplate
it's in the backend,
but the main
program logic should be as short
as possible and as easy to understand
as possible.
So I would say any application can benefit from some of those functional idioms.
I can see that, yeah.
So any other books you might have in the works? Or are you pretty happy just putting out this one and maybe going back to your past career without any more writing?
What do you think?
It sounds like you had so much fun.
Yeah.
Well, I did have some fun.
So if I ever get a time, two years, to do something like this,
I might write something else.
I recently got an offer to write a book on object-oriented programming in C++,
which was quite cool.
And I said, kind of, no.
I don't plan to write anything that serious in the near future, maybe in a couple of years.
Now, referencing the book that you have written and the joking writing an object-oriented
programming book, you have said a couple of times that functional programming is a tool for us it's one of many tools that doesn't replace object-oriented
programming in your book do you address how these tools interact with each other so i don't really
talk about how to combine object-oriented design Okay. Simply because... So the book is called Functional Programming.
My idea was to, let's say, teach more of C++
than people usually get taught during reading normal books.
So I wouldn't say that this is a completely separate world or anything else.
This is just another book that can improve your C++ toolbox.
Okay, that makes sense.
I think most of the things that I
presented there, as I said,
I didn't say explicitly
how you combine something with OOP,
but I think for
because the book is written for
let's say experienced C++ developers,
I do think that
all of them can easily mix and match
without any examples for me.
Okay, that makes sense, yeah.
Do you have any upcoming talks or anything planned?
It sounds like you do give some talks on functional programming, right?
Yeah.
In the past year, I had a little bit too many.
Okay.
So I kind of decided to rest a bit.
So the only plans that I have
are meeting C++
and C++ Russia in
St. Petersburg.
Although I'm trying to move a little bit away from
functional programming because I don't want
to be forever known as the functional guy.
Okay, well it's been great having you on the show today even yeah it was really fun and thanks for
joining us thanks thanks for inviting me thanks so much for listening in as we chat about c++
we'd love to hear what you think of the podcast please let us know if we're discussing the stuff
you're interested in or if you have a suggestion for a topic we'd love to hear about that too
you can email all your thoughts to feedback at cppcast.com we'd also appreciate if you have a suggestion for a topic, we'd love to hear about that too. You can email all your thoughts to feedback at cppcast.com.
We'd also appreciate if you can like CppCast on Facebook and follow CppCast on Twitter.
You can also follow me at Rob W. Irving and Jason at Lefticus on Twitter.
We'd also like to thank all our patrons who help support the show through Patreon.
If you'd like to support us on Patreon, you can do so at patreon.com slash cppcast. And of course, you can find all that info and the show notes on the podcast website
at cppcast.com. Theme music for this episode was provided by podcastthemes.com.