Tag: functional programming

Is C++ Ready for Functional Programming? – Wrap Up

Wrap Up

Recently I had the questionable pleasure of watching “Cosmic Sin” courtesy of Netflix. The movie is a sci-fi show starring Bruce Willis. I was lured into wasting my time on it, by the trailer promising a space-operish feat and I took the presence of such a star playing in the movie for a warranty on quality. I couldn’t be farther from the truth.

The movie plays out confusingly, lacking a coherent script and motivated actors, pushing the watcher into an undefined state (not UB luckily). The helpless watcher, astonished by how bad a film could be, hopes until the very last for something interesting and entertaining to happen until the mixed relief-disbelief emotion of closing titles puts an end to the suffering.

When thinking about C++ and functional programming I have some of the feelings I had watching the movie. Before being persecuted by my friends from the C++ community I have to make clear that C++ is not that bad, although there are some similarities.

Continue reading “Is C++ Ready for Functional Programming? – Wrap Up”

Is C++ Ready for Functional Programming? – Types

Types

Featured image vector created by brgfx – www.freepik.com

Although functional programming can be done in a dynamically typed language (Lisp, the functional programming language forerunner, had no types), strong static type adds a very natural complement to functional programming.

From a mathematical point of view, a function sets a relationship between the set defined by the function argument (domain in math speaking) and the corresponding results (co-domain). Algebra studies exactly these relationships and may help the programmer in proving certain properties of the functions composing the programs.

Algebraic Data Types (ADT) are aggregated types in the algebra context. Two ADTs are of particular interest – sum types and product types. With sum and product referring to the resulting number of possible values (i.e. cardinality of sets).

Continue reading “Is C++ Ready for Functional Programming? – Types”

Is C++ Ready for Functional Programming? – Standard Library

Time to take a closer look to the standard library from the functional programming point of view.

In the first installment of this series, I stated that using a library to implement functional programming structures would not be an ideal solution, but as C language pioneered in the 70s, part of the language finds its proper location in a library.

C++ standard library has grown disorderly oversize during the years, so let’s have a look at what kind of support is available for those that want to use C++ with the functional paradigm.

Continue reading “Is C++ Ready for Functional Programming? – Standard Library”

Is C++ Ready for Functional Programming? – Functions, Functions for Everyone!

In this second installment, I’ll look closer to the core of functional programming – functions. When I started programming, BASIC was the language of choice… the only available choice. And no, it wasn’t the quite convoluted Visual Basic, but the old plain, primitive BASIC with line numbers and poor syntax.

In those days I just used GOTOs and looked with suspicion at the GOSUB/RETURN wondering why in the world I would need to automatically return when I could GOTO everywhere I needed… But I’m digressing. It is just for saying that (besides yours truly could be not the best authority on this matter), programming languages have come a long way and the poor BASIC programmer had to spin the evolution wheel for quite a while to reach to concept of function as presented in this post.

Continue reading “Is C++ Ready for Functional Programming? – Functions, Functions for Everyone!”

Is C++ Ready for Functional Programming? – Intro

Design by committee (DbC) was never meant to be a compliment. In DbC, every decision has to go through a debate and be subjected to a political process. Because of the needed compromise among the parts, the resulting artifact usually tends to be clunky and patchy, lacking elegance, homogeneity, and vision.

C++ is quite an old language, not as old as its parent C, or other veterans of the computer language arena, but the first standard is now 23 years old and the language was quite well-formed and aged to mature its dose of quirks, long before that.

Continue reading “Is C++ Ready for Functional Programming? – Intro”

Comprehensive For in C++

Switching back and forth between Scala and C++ tends to shuffle ideas in my brain. Some ideas from Scala and the functional world are so good that is just a pity that can’t be applied directly and simply in C++.

If you carefully look into idiomatic C code for error handling, it is easy to find a lousy approach even in industrial code. I’ve seen a lot of code where not every return value was examined for an error, or not everything was thoroughly validated, or some code was executed even when it was not needed because an error occurred but was too cumbersome to provide the escape path.

In C++ things are a bit better, thanks to the exception mechanism, but exceptions are such a pain in the neck to get right and to handle properly that error management could soon turn into a nightmare.

Error handling in C and C++ is so boring and problematic that the examples in most textbooks just skip it.

(featured image by Nadine Shaabana)

Continue reading “Comprehensive For in C++”

Our Fathers’ Faults – The Chain of Death

The functional programming core concept is about composing functions together to craft more complex and convoluted functions. In Scala (not unlike what happens in many other programming languages) there are two ways to combine functions: the first is to apply a function to the result value of another function and the latter is to use a function to produce the argument value of another function.

Written in this way they may look not so different, in fact, even if in practice they show up in quite a different look, the abuse of the mechanism leads to the same problem.
The first way of combining functions, is also called chaining since you chain functions together – the result of function fn is the input of function fn+1. (Interestigly this very same mechanism will get a boost in C++ starting from C++20 ISO standard thanks to range and pipes).

Take the following example:

List(1,2,3,4).filter( _ > 2 ).map( _.toString ).fold( "" )( _ + _ )

(If you already know Scala, you may safely skip this paragraph 🙂 ) If you are unfamiliar with Scala or function programming this may look suspiciously like bad code, (this could be some meat for another post), but trust me it is not. Function List(…) constructs a List. List, containers, and iterators in general in Scala have a set of methods that can be chained together. You may think of them as taking an iterator and producing an iterator in a different sequence. Back to the example above, filter produces an iterator that scans only elements of the input sequence that fulfill the given condition (being greater than 2 in the example). map produces an iterator over a sequence whose elements are computed by the given function on the source elements. Eventually fold collapses the sequence by accumulating items iteratively using the provided expression.

Each small block performs an operation. Note that I haven’t written “simple” operation, on purpose. In fact the operator (filter, map, fold) is simple in itself, but it is programmable via a lambda that can be as convoluted as you want. Therfore the operation performed by the block may become really complex.

While you are focused on your goal, it may be easy and convenient to dump your mind into an endless chain. This has two drawbacks, first, it is unreadable and second, it is uninspectable.

It is unreadable because you need to start from the beginning and analyze the sequence up to the point to where you want to focus and know what the inputs are and from there onward to understand how the output is processed into the final result. Pair this with complex lambdas and you may find yourself in quite a nightmare to figure out what this code is supposed to do or where is the bug.

It is uninspectable because you cannot use the debugger to stop execution and show intermediate results of your operation (I’ve noticed over the years that Scala programmers are usually reluctant in using a debugger preferring print/log debug).

The other form of the problem – functions calling functions calling functions – despite the differences in syntax, is not that different in how it is produced and in the result. The code you may see, such as –

context.become(
    enqueuer(
        resourceManagement(
            Queues( queues.execution.filterNot( x =>
                ( x == realFree || context.child( childName( x.getUUID ) ).isEmpty ) ), queues.waiting ) ) ), true )

can be written in any language, but it seems that our fathers was quite fond of this approach.

It is important to recognize that when writing code you have (or, at least you should have) a crystal clear and detailed comprehension of the data flow, and even if you strive to write clear code, you’ll tend to pack these things together because a) it is faster (less typing, less naming of values, less effort to add structure) and b) you don’t feel the need to make it clearer since it is so straightforward in your head.

Lesson learned – resist the temptation of dumping the mental flow into a coded data flow, use the old “divide et impera” to split the flow into manageable units with names reflecting the content e the intent. A good indication is the line length, if your statement, properly formatted to fit in 80 columns, happens to span over more than 3 lines, then splitting it is a good idea.

Additional thought Attending some FP conferences I had the clear impression that FP pundits encourage complex aggregation of functions, even the justification for having short indent space (2 characters is the recommended indentation for Scala) has the purpouse of make the writing of chains more convenient. For these reasons I suspect that this point could be a little controversial in FP circles. I stay with my idea that industrial quality code must be first easy to read and understand and then easy to write.

Lambda World 2019

Lambda World 2019 Blog Post

The Spanish town of Cadiz lies outward in the ocean, circled by ancient walls, protected by two castles. Grids of alleys, old houses facing at a short distance across narrow streets, narrow balconies enclosed in windowed structures. Warm, light brown rocks and stone. Old, ancient, historical and yet so filled with sun and sparkling energy.
It is just a heck of a journey to get there to attend the best functional programming conference in the world. You start from your ordinary small northern Italy town, get by car to the nearest airport, fly first to Barcellona, hoping that the turmoils for the recent sentence on the separatist leaders cause no problem with your flight exchange. Wait for a while at the airport terminal, eating a sandwich, then you board on another plane that will carry you to Jerez de la Frontera. There you are up to a ride on the train. Eventually, you reach Cadiz, but you still need to walk to your hotel in the historic downtown. “Walk” because at Cadiz core everything is at a walking distance and most of the streets are impractical to any car.

This is my third year in a row that I manage to get my employer to sponsor my attendance at Lambda World Cadiz. I like this conference, I like the eclectic view of the functional-programming-verse that provides and last, but not least, I like the setting.

Continue reading “Lambda World 2019”

If the free lunch is over, where can we eat for free?

In the first part of this blog post, I wrote about why FP is mandatory for programmers that work on modern software projects. Summing it up, it was like this – modern hardware scales up by adding cores, therefore, if software wants to scale up and well, then it has to do it by going concurrent, and FP is a good choice to deal with concurrent programming issues.

In this post, I’ll write about some differences between traditional and FP programming and I’ll present one more reason about why FP is a good match with parallel programming.

You can write bad code in any language. That’s a fact. So there’s no magic in functional programming to turn a lame programmer in a brilliant one. On the other hand, you can write pretty good code in the functional paradigm by sticking with the tools provided by functional languages.

So, let’s have a look at this FP thing… First, it is evident that this is not your parent’s FP – map, filter, fold… Just a few of the most recurring spells you’d see in a Scala source and none of them was in the notes I jotted down during my University courses. Even looking at my LISP textbook I couldn’t find any reference to the map operation. (Just to help those with no FP background – map (transform in C++) is an operation that applies a transformation to each item in a collection. In other words, if you have a function that turns apples into pears, then – using map – you can turn your array of apples into an array of pears.)

Continue reading “If the free lunch is over, where can we eat for free?”

Lambda World 2018

Back in the XVI century, the Flota de Indias based in Cadiz set out to Americas carrying tools,  books, and settlers and carried back goods, from the new world.

In much the same way I went to Cadiz and set off for the brave new world of functional programming with the intent of carrying back news and techniques for my daily job.

Cadiz is an awesome and is a wonderful frame for one the best conference I attended in 2017 and 2018 – Lambda World.

As usual, I took a lot of notes and possibly soon or later they will land here. I plan to prepare a short summary with information about the conference and briefs of the speech I attended, much I did for Scala Italy. In the meantime, I warmly suggest these awesome notes (by Yulia). Stay tuned.