Cogs and Levers A blog full of technical stuff

Viewing RDoc Sets

You can start an internal web server that will serve all of your installed gemsets’ documentation simply by issuing the following command at the console.

$ gem server
Server started at http://0.0.0.0:8808

Point your web browers to the machine on port 8808 and you’re away!

Lambda Expressions with C++11

Introduction

A whole raft of goodness has been delivered with the most recent C++ standard, C++11. One of these features is the inclusion of lambda expressions. Today’s post will take you through the basic syntax for lambdas in C++.

Basic Assignment

You can assign a lambda to a variable quite simply with the following syntax.

#include <iostream>

int main(int argc, char *argv[]) {
  // assignment to an "auto" variable
  auto f1 = [] { std::cout << "Hello, World" << std::endl; };

  f1();

  return 0;
}

I agree that this is a pretty ass-about-face way of printing “Hello, World” to the screen - but it’s done through C++11’s lambda syntax. Passing variables into a lambda expression and getting return values is quite trivial also.

// implicit return types (handled by the complier)
auto add_imp = [] (int a, int b) { return a + b; };

// explicit return types (specified by user)
auto add_exp = [] (int a, int b) -> int { return a + b };

You can nest lambdas pretty easily also. Heres is a multiply-then-divide example where the division operation is the nested operation. Multiplication occurs at the top-level lambda.

auto muldiv = [] (float a, float x, float y) {
  return [] (float v, float u) {             
    return v / u;                           
  }(a * x, y);                               
};                                            

This syntax also allows you to define higher-order functions, so that you can return function object back to the caller for later use. Here, I’ve made a multiplier factory. You give it one side of the multiplication and it’ll hand you back a function that will multiply by that number.

auto mulBy = [](int x) {
  return [=](int y) { return x * y; };
};

auto mulBy2 = mulBy(2);
auto mulBy10 = mulBy(10);

We’ve done something a little bit different here. You can see that we’ve used a term inside the square brackets for the returned function. C++ having a major focus on performance gives the developer as much flexibility as possible when handling values. The information specified within the square braces tells the lambda closure how to handle variables referenced within.

Handling outside state within a lambda

The developer describes to the lambda how she wants variables captured by making specifications within the square brackets. Some examples of what you might see look like this.

Specification Meaning
[] Don’t capture anything
[&] Capture any variable by reference
[=] Capture any variable used making a copy of it
[=, &x] Capture any variable used making a copy of it except for x. Capture x by reference.
[y] Capture y by making a copy but nothing else.
[this] Capture the enclosing class’ pointer

So, we can be quite specific in telling the compiler how we want referenced variables handled within our lambda closure. Finally, I want to present some code on using lambdas with existing constructs. In this example, I’ll reduce a list of integers by accumulating them into a variable referenced outside of a closure.

#include <iostream>                              
#include <vector>                                
#include <algorithm>                             

int main(int argc, char *argv[]) {               

  // vector to reduce
  std::vector<int> l;                           
  l.push_back(1);                               
  l.push_back(2);                               
  l.push_back(3);                               

  // reduced result
  int i = 0;                                    

  // reduction by accumulation
  std::for_each(l.begin(), l.end(),             
    [&i](int n) { i += n; }                    
  );                                            

  std::cout << "reduced to: " << i << std::endl;

  return 0;                                     
}                                                

You can see that is is quite a fluent style for writing lambdas. This post only scratches the surface. Applying these in a real project is going to be key to discovering the depths of lambdas, but they’re alive and well in C++(11) land, that’s for sure.

C++ References

Introduction

I’ve always thought of a reference as the half-way house between pointers and statically allocated objects. References are in-fact addresses but they are used within our code just like objects as opposed to requiring pointer syntax.

Some facts ..

How reference are defined

You declare a reference variable using the ampersand & to modify the type declaration.

type& var;

A reference must be initialised

This is pretty basic, it just means that when you declare your reference it must start out with a place to reference.

// this is ok
int val = 90;
int& ref = val;

// this will not compile
int& ref;

A reference cannot be changed

When we initialise a reference to point to a variable, that’s it. We can’t change what the reference points to. This caught be out to begin with, but it’s pretty easy stuff.

int val1 = 90, val2 = 100;
int& ref = val1;

// prints out "90"
std::cout << val1 << std::endl;

// doesn't change ref, but changes the value
// of val1 to val2
ref = val2;

// prints out "100"
std::cout << val1 << std::endl;

Makes sense. Gives references a sense of stubbornness (and sanity).

Pointer compatibility through dereferencing

I see a fair bit of banter on “how to convert pointer to reference”, etc. It’s really quite simple and it’s also subject to the same assignment laws as above.

int i = 50, j = 60;
int* p = &i;
int& r = *p;

// prints 50 
std::cout << *p << std::endl;

// through this reference, we've changed "i" to 60
r = j;

// prints 60
std::cout << *p << std::endl;

These concepts really come into their own (I think) once you start using them within your own class structures. It’s a much more natural feel to deal with references rather than pointers and a bit easier to read as well.

Writing a Window Manager for X11

As a bit of a bookmark to myself, I just wanted to post about writing a window manager for X windows. A lot of the material that I’ve seen around the place in articles and posts themselves have all pointed me towards downloading the out-of-print O’Reilly Open Book site.

Some of the books of interest to a window manager programmer are

I’m sure that there is plenty of other reference material around, but a lot of people were suggesting to put a copy of these in your claw - so I have. Digging around a little bit more, I came across TinyWM. TinyWM looks like a suitable candidate to be the bootstrap to a window manager project. It’s functional, it doesn’t do much but it is around 50 lines of C code. I’ll be using this as my guide for when that rainy day comes and I start work on my own WM.

Clojure's spine: Java

Introduction

One of Clojure’s greatest strengths is the fact that it sits on the JVM. This puts all of those jars that people have worked tirelessly over the years to produce right at your fingertips ready for use in your Clojure code. Today’s post will just be a short tutorial on some of the most basic routines to use Java classes in your Clojure code. All of the examples that I’ll produce are all based on the Java_interop page on the Clojure site.

Importing classes

First things first. You’ll need to import the classes that you want to use. You don’t have to, it just makes your code a little less verbose later on.

(import 'java.net.URL)

We’re now able to use the URL class in our code. If you’re importing classes into your programs that aren’t local and need to be downloaded as a dependency, I suggest you use Leiningen to do all the heavy lifting for you there. You’d just need to list your external package in the dependencies list in your project file and away you go.

Using the classes

We need to construct some objects so that we’ll be able to call methods on them, so following on from the example, we construct instances of the classes that we import like so.

(def google (new URL "http://www.google.com"))

This is really getting the Java mojo mixed in with Clojure now. So “google” is our constructed object, we can start to call methods on this variable like so.

(.getProtocol google)

(def yahoo (new URL "http://www.yahoo.com"))
(.sameFile google yahoo)

We were able to find out the protocol of the URL using getProtocol and we were able to compare “google” and “yahoo” using sameFile.

doto

The last thing I want to talk about is doto. doto evaluates its first parameter than allows you to chain a series of calls (just as you would in Java using the . operator) together. Here’s a an example using a HashMap class and chaining a few put’s together. This statement will return the built HashMap.

(doto (java.util.HashMap.)
      (.put "First Name" "John")
      (.put "Last Name" "Smith"))

Well, that’s it for today. I’m off to write some Java .. I mean, Clojure, I mean … you know what I mean.