Facets of Immutability

Immutability, the cornerstone of functional programming, has many facets.

Not every (mainstream) language supports all the facets; at least not per what each facet stands for. That’s what I will talk about today. The various facets of immutability from a theoretical perspective, and briefly show how some of the mainstream languages have adopted and support these facets in their own way.

Continue reading Facets of Immutability

Advertisements

Writing sonnets in C++

Recently, I came across this post – Write a URL in a C++ program, one of those C’s tricks. If you have not already read the post, I will wait until you read and return …

waitingWaiting …

The crux of the trick is the protocol part of the URL – http:, becomes a goto label and the rest of the URL starting with // becomes a comment. Sweet 🤗

My turn My turn …

Continue reading Writing sonnets in C++

Publishing C++/CLI on LeanPub

I came across LeanPub a few months back. I believe it was through hanselman – blog, video or something. I liked LeanPub instantly because of a couple of reasons.

  • It supports writing in markdown and I love markdown.
  • There is a large collection and variety of books including technical books and material, some of which are free too.
  • In case you are not a professional writer, the publication process encourages you with the feeling as if you are one.

I hadn’t written/published any lengthy material in a long time except the C+/CLI Primer on CodeProject. Why not publish same, I thought, and actually published. I wasn’t even expecting any response from anyone since the material was on C++/CLI, a language that gave me the impression that I was the only one using it at the time I published on CodeProject. 😀 I am really impressed that the material topped more than 50 downloads in about three months since it was published. Heck, a couple of them even paid despite the fact that the material is free. Not only am I humbled by this encouraging gesture but I am also convinced that C++/CLI is still being pursued and will continue to live – production, academic or as a pet language. Go grab your copy of the booklet – C++/CLI Primer. It’s free!

final, const and beyond

What are your thoughts on the following piece of code?

public String someGibberishMethod() {
    int length = someMethodReturningLength();
    int sum = 0;

    for (int index = 0; index < length; ++index) {
       // some code that updates the sum variable
    }

    SomeClass someClass = new SomeClass(sum);
    int sumValueInsideSomeClass = someClass.getSumValue();
    // use someText, maybe log or something

    String someText = someClass.doSomeOperation(/*some parameters*/);
    // use someText, maybe log or something
    return someText;
}

Continue reading final, const and beyond

An Unfair World of Tuples, Anons., var and auto

It all began when I wanted to return more than one value from one of the methods. Although my attempts ended futile, it was fun exploring and musing how things could have been.

There are at least a couple of options to return multiple values from a method:-

  1. return an instance of a class that holds the values
  2. return a tuple

Continue reading An Unfair World of Tuples, Anons., var and auto

Crazy Braces – [](){}();

What does this cryptic sequence of braces mean? What programming language is it? Is it valid syntax? If there is even a weak chance of this syntax being valid, then what does it mean?

Alright, alright, alright…..It is C++. That would calm most people; with all their love (pun) for C++. Specifically, it is C++0x. Amongst many other features that we have been waiting for, C++0x gives us the power of lambdas.

The formal definition of a lambda in C++0x is as follows:-

[capture_mode] (parameters) mutable throw() -> return_type {
   body
}

So a lambda may capture one or more variables in scope by value or by reference, or it may capture none. Specifying return_type is not necessary if the type can be inferred or is void.

For instance, a std::for_each‘s functor based code could be inlined with a lambda as follows:-

std::for_each(v.begin(), v.end(), [](int x) {
   cout << x << std::endl;
});

A lambda definition could be assigned to a variable and then used or invoked later.

auto lessthan = [](int left, int right) {
    return left < right;
};

In the above code, lessthan represents a function that takes two int parameters, and returns a bool. And it can be invoked as lessthan(2, 3), which returns true. The cute thing about a lambda is that it can invoked directly right after its definition. The following code defines a lambda (which takes two ints and returns a bool) and invokes it right away.

[](int left, int right) {
   return left < right;
} (2, 3);

Coming back to our initial question. You should have guessed it by now. The sequence of braces – [](){}();, is nothing but a definition followed by a call (right away) to a lambda taking no arguments and returning nothing.

To end with a quote, C++ code is like calligraphy. In other words, it is beautiful to those who understand it, while cryptic to others.

Quiz – Where am I ?

The question is, in C++, how do detect if an object is allocated on the stack or heap.

On Windows, the stack address is in the range of 0x80000000. If the address of the variable is in this range, then you could say that the object is allocated on the stack; else it is allocated on the heap. This technique of detecting is not preferrable since it may not work on other operating systems (such as linux), and deals with the platform specific information making it a non-portable solution.

Let us try to use standard C++ stuff to solve the problem. Ok, we want to know where an object is allocated. In C++, new operator is responsible for allocating an object.

It was very thoughtful of Stroustoup to keep the object allocation and initialization\construction separate. new operator is responsible only for allocation. The compiler is responsible for woving up the code for allocation and calling the constructor. It was also very thoughtful of being able to specify the location where the object needs to be allocated, which of course does not necessarily require overloading the new operator.

C++ allows taking control of object allocation by overloading the new operator. By taking control, you would be able to detect where an object is allocated, and also keep a count of the objects allocated on the stack\heap. The following code snippet illustrates the same:-

//
// SomeClass.h
//

#include <iostream>
#include <stdlib.h>
#include <deque>
#include <algorithm>

using namespace std;

class SomeClass;
typedef std::deque<SomeClass*>      SomeClassDB;
typedef SomeClassDB::iterator    SomeClassDBIter;
typedef SomeClassDB::const_iterator SomeClassDBConstIter;

class SomeClass
{
private: static SomeClassDB heapObjects;
private: static SomeClassDB stackObjects;

private: double value;
private: bool isOnHeap;

public: SomeClass(double d) : value(d), isOnHeap(SomeClass::IsOnHeap(this))
        {
           if (!IsOnHeap())
           {
              SomeClass::stackObjects.push_back(this);
           }

           PrintLocationInfo();
        }

public: ~SomeClass()
        {
           SomeClassDBIter iter = std::find(SomeClass::heapObjects.begin(),
                    SomeClass::heapObjects.end(),
                    this);

           if (iter != SomeClass::heapObjects.end())
           {
              SomeClass::heapObjects.erase(iter);
           }
        }

public: double Value() const
        {
           return this->value;
        }

public: bool IsOnHeap() const
        {
           return this->isOnHeap;
        }

public: bool IsOnStack() const
        {
           return !IsOnHeap();
        }

public: std::string Location() const
        {
           return IsOnHeap() ? "Heap" : "Stack";
        }

public: void PrintLocationInfo() const
        {
           std::cout << Value() << " is on " << Location().c_str() << std::endl;
        }

private: static bool IsOnHeap(SomeClass* scPtr)
         {
            SomeClassDBConstIter iter = std::find(SomeClass::heapObjects.begin(), SomeClass::heapObjects.end(), scPtr);
            return iter != SomeClass::heapObjects.end();
         }

private: static bool IsOnStack(SomeClass* scPtr)
         {
            return !IsOnHeap(scPtr);
         }

public: static void* operator new(size_t size)
        {
           SomeClass* scPtr = (SomeClass*)malloc(size);
           SomeClass::heapObjects.push_back(scPtr);
           return scPtr;
        }

public: static void operator delete(void* ptr)
        {
           free(ptr);
        }

public: static size_t HeapCount()
        {
           return SomeClass::heapObjects.size();
        }

public: static size_t StackCount()
        {
           return SomeClass::stackObjects.size();
        }

public: static void PrintObjectCount()
        {
           std::cout << "OnHeap: " << HeapCount() << " .... OnStack: " << StackCount() << std::endl;
        }
};

//
// SomeClass.cpp
//

#include "SomeClass.h"

SomeClassDB SomeClass::heapObjects;
SomeClassDB SomeClass::stackObjects;

int main (int argc, char *argv[])
{
   SomeClass sc(0.123);
   SomeClass* scPtr = new SomeClass(1.234);

   SomeClass::PrintObjectCount();

   {
      SomeClass sc1(2.345);
      SomeClass::PrintObjectCount();
   }

   delete scPtr;

   SomeClass::PrintObjectCount();

   return 0;
}

You should be aware of implementing the custom delete if you have provided a custom new operator. It is logical because only a custom implementation that allocated memory for the object could possibly know how to deallocate. The above technique of overloading new\delete is portable and safe since it is standard C++. As always, writing standard C++ is fun.

But why would one care to know where an object is allocated or keep a count of objects. I don’t think it would something you would require for production purposes. It could be for development\debugging purposes; maybe you want to detect memory leaks or a general distribution of objects. You could take control of the allocation by overloading new for a particular class or for all classes by declaring a global new operator.