Today’s Topic: map()
1. Apologies
I would just like to start by apologizing for the code that I have written. It is a naive approach to beginning work on a few of the basic constructs of functional programming in C and C++. It is not pretty, and it is not necessarily perfect. It does, however, work. I created some data structures to more closely emulate the syntax I desired, and I am in no way vouching for my code as being the best possible solution.
2. Implementation
Instead of dumping code here, I will discuss just the relevant function, to make the overall lack of elegance more palatable. I will also show how one would invoke the map function.
To explain a few things before we jump into code, in an effort to beautify the hacked-together code that was sure to follow, I created a few constants and structs. Firstly, I defined a constant called LIST_SIZE that I passed around to define the size of any array used in this code.
I also created a struct called SIZED_ARRAY that takes a type and an unsigned int, and creates an array of the specified type that can hold the specified number of elements. This array is templated in such a way that the size of the array is carried with the array itself.
Simple, right? Invokation of the map function, thanks to GCC inferring template parameters from arguments, is even simpler. So we have a function called multiply_two that takes an int and returns double that value. We could simply map that function to a list of values and now we have a map function, much like one would find in Haskell, or similar languages.
3. Source Code
The entire source code is available here: map.cpp