A funny thing about programming is: if you don’t feel a bit ashamed of stuff you have written in the past, you didn’t improve. And now that I’m reading some things on this blog again, I feel a bit ashamed. I hardly explained what is so good about Common Lisp, and some other things now feel factually wrong. Now my tastes also changed a lot, giving more value to powerful type systems and safety in general than to the apparent flexibility of dynamic languages.

Anyway, enough of introduction. I’m here to talk about one hell of impressive language called Rust.

The system programming languages’ current scenario

Well, before starting talking about Rust itself, a bit of context: Rust is aimed to be a powerful, expressive, and, more than all, safe system programming language (which I’ll call SPL for shorts from now on). Other SPLs include C, C++, D, and *sighs* Go.

A SPL, of course, is a language designed to create systems, which are softwares that operate the hardware and provide an abstraction for high-level applications. So, you need abstractions closer to hardware, like types that mimic how bytes are moved around, you should be able to control every single piece of performance, so the language should avoid any kind of overhead (like runtime type checking or garbage collection).

C and C++ are the two languages that dominate this scene. Most Operating Systems nowadays are written in C (like Linux), and some in C++ (like Haiku). There are historical reasons for that (for instance, the fact that UNIX is the basis for most operating systems nowadays), but it’s not impossible to replace them.

D was created as some kind of C++ substitute. Unlike C++, it is a proper C superset, but included a Garbage Collector (that may be avoided), true immutable data, a more explicit functional style, among lots of other resources.

Go was created with… modern languages in mind, like Python or Ruby. Which I don’t see how it should work: as I said before, a SPL must not have runtime type checking or garbage collection, and Go features both because they are “more modern” approaches.

Both D and Go try to solve lots of known problems from C and C++ that are now stuck on their design. C is too simple, and it will remain this way. C++ is too bloated, and there’s nothing to be done on it.

Now, Rust aimed at solving a different scope of problems, with a different set of strategies. Rust dares to be safe.


C and C++ aren’t safe. There are lots of ways your program can go wrong: you can have dangling pointers, segfaults, buffer overflows, mutability can hit your threads with a race condition, you can dereference the wrong type…

D and Go solve some of these problems, but not always in a pretty way (like having memory safety using a GC), and not all problems (I’m looking at you, Go’s empty interface).

Now, Rust if safe because it aims to solve most of these problems in compile time.


Every Rust object is immutable by default, unless you specifically mark them as mutable. Besides, there’s no shared memory between threads (which is funny, considering Tanenbaum’s definition of threads). Concurrency is not exactly an unsolved problem, and in fact lots of languages aim to solve it in different ways, like Clojure, Haskell or Scala.

Type safety

Now, Rust’s type system is very powerful, compared to the cited languages (maybe not C++, but then, C++’s type system became a mess). It’s not as powerful as Haskell’s, but, for a system language, it feels like it.

Enums are actually algebraic data types disguised. It has type inference. It has traits. Variables can’t hold null pointers (you need to use the algebraic type systems to have something similar. The standard library has the Option<T> enum for that). It may even get better with time.

Now, the most impressive thing about Rust’s type system is that it also provides memory safety in compile time. But how is that?

Memory safety

Rust’s type system is linear. It can assure that an object has exactly only one reference, and if that reference is lost, the object will be deallocated. If you want to pass this object somewhere else, you either have to move it (so you won’t be able to use the previous reference again), or to borrow it (you can only borrow objects if the compiler can assure the original reference will keep living after the borrowed one has died).

That makes it possible to predict the lifetime of every object in compile time, and allocate and deallocate them as necessary at runtime, without resorting to a GC (or any other runtime overhead).

Surely you can use raw pointers just like C or C++, when owned pointers and borrowed pointers can’t express some data structure you need, like doubly linked lists. But you need to mark the blocks where you use them as unsafe. So, if you do have a memory problem, you’ll know where to look. There are also data structures for reference counting or garbage collecting.

Final considerations

Rust is still unstable, so you shouldn’t use it for anything that will go for production. It is still a laboratory, where you may explore and try to apply its concepts. But, honestly, among all the modern SPLs, Rust is the one which shows the most potential, by providing an actual new solution for the biggest problem of any SPL without resorting to any runtime tricks: safety.

Getting open for new paradigms

I think that all you five readers (ok, I’m being too generous) of my blog know that I love Ruby. Well, I’ll tell you why I haven’t posted in awhile: I have met someone new, and now Ruby only feels… well, it is still pretty good, it just is hiding even better stuff from me.

Yes, that’s right. I’m learning that old-fashioned, parenthesis-filled, known as crappy language called Common Lisp. And… well, parenthesis is a silly reason for you to not learn it, too.

I tried to make a long post explaining why the language is good, but it would require a book. So, instead, I’ll post a link to Practical Common Lisp and tell some things that may convince you:

Ruby’s internal object system is based on Emacs Lisp’s object system. Emacs Lisp’s object system is based on CLOS (Common Lisp Object System).

So imagine all the power of Ruby’s internal typing and message passing (which in Common Lisp is actually message dispatching, and for good reasons), but exposed to you, everything modifiable.

Code is data. Data is code.

Everything in Lisp is composed by S-Expressions, which is simply a syntax for linked lists. And the language has lots of functions to manipulate linked lists. Yes. Yes, you can manipulate your code with these concepts.

First-class functions and lambdas are more flexible than Ruby’s blocks.

You can easily have more than one function as a parameter on Lisp. You can pass a function as a block more easily. For instance, compare this:

[3, 1, 2].sort { |x,y| y <=> x }

With this:

(sort '(3 1 2) #'>)

In the second case, you’re passing the “>” (higher than) function directly to the sort function. On the case of sort it may not be much, but see how you multiply all the elements on your array:

(reduce #'* '(3 1 2))

What if I need to pass a custom function? Well, use a lambda:

(sort '("a" "def" "bc") (lambda (x y) (< (length x) (length y))))

And if I’m creating a function that receives another function? Ruby has yield, is Common Lisp as easy?

Yes. Funcall:

(funcall <variable storing the function> <arguments>)

It can be interpreted, but it can also be compiled.

You can compile Common Lisp code to native code and run it with a great speed, unlike Ruby, which needs to be interpreted or to run under a virtual machine. And yet, you have the facilities of an interpreted language, as garbage collection, on the fly evaluation, first class functions and closures.

Common Lisp isn’t functional, as some people may seem to think.

As I’ve said before, Common Lisp has a powerful object system. It may give support for imperative style programming and declarative style programming. Most lispers seem to have some preference for functional and declarative programming, because it’s often shorter and more trustful. So, don’t be afraid of Common Lisp because of something like programming paradigm: it will fill your needs.

If you complain about lack of libraries, you shouldn’t have started to use Ruby in the first place.

Using something only because it’s popular leads to average technology, not better technology.

I mean, Ruby is good. But you should try Common Lisp yourself and see if it’s better.

If parenthesis bother you, try a good editor, most of them have great navigation for it.

About Richard Stallman and Ubuntu’s dash

For anybody that follows all the GNU/Linux drama that always happen one day or the other, the Amazon search on Ubuntu’s dash is not news. But for those who aren’t informed, here we have some context:

Ubuntu 12.10 brought us a polemic new feature on Ubuntu’s dash. When you type your search on dash, where previously you had only files and applications, now you also have Amazon’s shopping suggestions. This brought rage and privacy concerns to its users, because the terms were not encrypted before being send to Canonical, and because it was enabled by default.

They solved the encryption concern. But not the default enabling. Nor they warn or inform the user in any way during the installation process.

A lot of users tried to suggest solutions to this issue, but Canonical only made it possible to disable this with an option (but it was still enabled by default).

Now, Richard M. Stallman himself published an article, calling this feature a “spyware”, and also suggesting how to address the problem.

As a response, one of Ubuntu’s contributor made his own article saying that people should stop complaining and should instead help make Ubuntu better.

Also, Ubuntu’s Community Manager, Jono Bacon, made another response saying that RMS is actually spreading FUD.

Now, my personal opinion on this issue:

First, linking to launchpad does not address the issue. As I said before, lots of people tried to propose a solution for this problem on launchpad, but they were ignored. Even some satires appeared (saying that using “find” on the CLI did not return Amazon’s results). If Canonical does not want to accept user’s suggestions, how is it true that WE make Ubuntu better? Canonical must accept patches and valid suggestions if it really wants to be free and open.

Also, the “linking to launchpad” is actually very, very dismissive. It seems that Mr. Randall is trying to say that all this are user’s fault. No. It’s not.

When he said that everybody should try to help, he seemed to ignore that Stallman gave his own suggestion on how to make dash better (a button for “search locally” and another for “search on the web”). What’s so difficult about this?

And also, why should Stallman still worry about coding this? Ubuntu runs on top of his Operating System. There wouldn’t be Ubuntu if there wasn’t Stallman. Mr. Randall shouldn’t have forgotten this.

About Bacon’s response, I’ll only say one thing: this is not FUD (Fear, Uncertainty and Doubt). Stallman is very well informed about dash. Stallman’s readers are also well informed. The group of people that isn’t informed is anybody that didn’t deactivate this feature because they wasn’t informed of its existence, nor how to deactivate that.

This feature is even worse than all the free applications that try to install the Ask toolbar on a Windows machine. At least they ask the user if he wants to install the toolbar. Ubuntu is not even doing this.

Concluding, this is NOT a coding issue, this is NOT a help absence issue, this is an ETHICAL issue, and should be addressed as one. Canonical’s dismisses only make it looks worse.

WebloggerMode apparent bug

I create entries on my blog through “WebloggerMode”, a package for Emacs. Yesterday, when I tried to post my previous entry, I noticed that weblogger was setting the date of my entry to “31 Dez 1999 21:00:00 -0300”. That was really… unpleasant. I don’t want to need to open to make things work. And, besides not having categories, only keywords, WebloggerMode was working just fine to me.

Well, the first thing I done was to send an email to WebloggerMode discussion list. The developer of the mode himself asked me if I tried to track down the bug (I was in a hurry when I detected it, so I didn’t read the code profoundly) and the URL for my blog. I promised to try to track down it.

Today, I started to think about potential solutions. I gave one more look to the code, and didn’t see anything really wrong. Nothing on xml-rpc.el either (which is a dependency for weblogger).

So I remembered that there are some extensions that should be loaded with the “require” function, while other only work with “load-file”. I checked the wiki and… load-file. I checked my .emacs and… require. I corrected it and it worked as usual.

Well, just myself being dumb again. Who would say?

Emacs, Emacs, why not Eclipse?

I’m an android developer, meaning that most of my job involves Java and XML. There is a lot of circle-jerk (I don’t know a better word for it, unfortunately) regarding these two technologies, and in fact I see some problems with Java, indeed. But it is a tool that does a good job at the end of the day, and JVM is a good and mature technology.

With all my “Emacs this, Emacs that”, maybe you’re thinking why I don’t using a “modern” IDE, like eclipse or NetBeans.

Well, since I’m a android developer, I actually use eclipse on my day-to-day work. There are three main reasons for that.

  1. Java is a dense language, with lots of classes and methods and types. With Android’s SDK, this is get even bigger. An IDE helps me to find myself out.
  2. ADT is really well integrated with Eclipse, providing a lot of features that are easily accessed.
  3. I never really got JDEE working on Emacs 24, much less android’s modes.

Since Emacs’ shortcut keys are starting to get hardwired in my brain, I installed the extension called Emacs+ (only available on Eclipse Indigo). There are a few things that I miss (if only it were a ELisp parser…), but I’m mostly happy with it.

Well, mostly. There are a few things that I really dislike about eclipse. When it gets in my way. When it doesn’t recognizes things that are there. When there is no other easy way of doing a task besides going to the mouse.

But how does eclipse gets in my way?

Well, I don’t understand exactly how and why, but sometimes eclipse will “hold” a file and no other program will be able to use the same file, even if it is already saved and I’m not doing anything on it. This is a HUGE problem if you, like me, uses version control on the command line because of the flexibility it provides.

Sometimes eclipse will only let me use the file if I close it inside of eclipse. But sometimes I don’t want to. I want it to remain open, because it’s terrible to reopen it.

Maybe this is my fault. I really don’t know.

And what am I talking about when I say that it doesn’t recognizes things that are there?

Sometimes, eclipse won’t start the main activity because, for it, the activity does not exist. Even if it does. Even if I can open it directly on the device.

Finally, about going to the mouse: I’m an incorrigible keyboard adept. My text editor won’t ask me to use the mouse. My window manager will avoid the mouse. I hardly ever use my file manager because I find more practical to do a lot of tasks on a terminal. When I can’t do that on eclipse because it thinks that mouse is easier, I get pissed.

I know, I know that eclipse has lots of shortcut keys and I can edit them. But it seems that eclipse is not meant to be used this way.

Oh, this reminds me of one last thing: customize eclipse is boring as hell. If it had a scripting language, like Emacs Lisp, vim script, Ruby, Python, or whatever, sometimes it would be just better. Eclipse is a programmer’s tool, why not benefiting from that?

Why I chose Emacs over other editors

Last time I posted, I told everybody to choose a text editor from a rather small list.

Again, the most known text editors are Emacs and vim. But other famous editors are starting to show up, such as Text Mate and Sublime Text.

Again, I don’t intend to say that Emacs is better than those, I’ll only list reasons to why it fulfills MY needs. I will try to analyze what I think it is so cool in Emacs, even knowing that some of there features are also on other editors.

  1. Emacs is really, REALLY easy to extend. Since Emacs is actually a eLisp parser which its main functionality is text editing, you can customize it using eLisp. That is: anything that you could do in eLisp, you can do in Emacs. Vim has also a scripting language, but it is not as powerful, nor it has as many extensions, as eLisp.
  2. Extensions (cont.). There are a lot of extensions for it. Really. As I said before, I write on my blog through Emacs. I could read and write email through it. I can talk through it on IRC on it. Hell, I can even play Tetris on it!
  3. Macros. Macros are among the most awesome things about Emacs. You can store a bunch of commands into a macro for executing it repeatedly later. This saves a lot of repetitive work.
  4. Shortcut keys. I really don’t like how modal editing works. It’s not intuitive to me, no matter how fewer keystrokes vim users actually type.
  5. AUCTeX (and other LaTeX extensions). LaTeX is awesome, and using it on Emacs is even more awesome. The amount of helpers that Emacs has is amazing.
  6. Rectangle manipulation. Yup, you can manipulate regions (how Emacs calls “selection areas”) in rectangle shape. You can insert strings, remove them, among other things. Inserting one-line comments in lots of lines is a pleasure with it.
  7. Windows, buffers and other concepts. You can divide your screen into multiple windows. You can open multiple buffers and switch freely between them.
  8. Ansi-term. You can access any shell (e. g. bash) inside of Emacs. Need to edit a file and execute a command through ssh? Well, open a new window and use the ansi-term.
  9. Daemon mode. You can run Emacs as a daemon (and open it at login, for example), and open clients for it. Every client shares the same buffers. This is great in any kind of environment.
  10. Tramp mode. Tramp mode allows you to access files directly through FTP, SSH, or anything like it, on your own computer, without worrying if the target machine has Emacs installed on it. No need for downloading, editing and uploading, nor installing the editor on the target machine.
  11. Package management. Since Emacs has a lot of extensions, the internal package manager is useful for quickly installing them.

Probably there are other things that I can’t remember at the moment. But if you use Emacs and can give more examples, please, leave a comment!

Learn to use a serious editor

After some insistence from a friend of mine, I decided to try emacs out. This gone for maybe a month, and… well, how could I say? I loved it!

Understand, vim users, I have nothing against you. Actually, after I started to learn emacs I gave vim a try, too. It’s just not what I expect from an editor. I don’t like modes, I like to type and something happens. If and when I want some command, I use shortcut keys. Emacs fills these needs.

I have been using emacs since last time I made a post in this blog. The amount of things you can do with it is amazing. I’m even writing this blog post on it.

But why should you use a serious text editor?

Well, there are a number of things that emacs/vim/text mate/sublime text can do that simpler editors can’t. The main one are macros.

Everything you type on a serious text editor is a command. Even when you insert a character you’re actually executing some sort of command. Macros stores every command you type, so you can use them again instantly. This is the most useful thing you can imagine, and only this would be worth trying a serious editor.

Serious text editors also handle rectangles manipulation. That is, you can select rectangle areas, insert characters in them, or delete them. This is REALLY useful for commenting big blocks of codes in languages that don’t have multiline comments (as Ruby, for instance).

Text editors are not IDE’s. You won’t compile or debug code directly on them, for this there are other tools, like make or GDB. But this is not what text editors intend to be. They are meant to edit your code, and only this.

Emacs has some IDE features with CEDET, but they are poor documented, confusing and not well abstract enough. I tried to use it, but it was clumsy and confusing.

So, don’t trust me. Take some time and start learning vim, emacs or any other serious editor that suits you best.

What I love about Ruby

I talk about Ruby all the time, even being proficient with other languages (such as C, Java and C# – but not C++). Why is that? Well, Ruby has a lot of incredible features that you may find on other languages, but generally are not on static languages:

1 – Code blocks and lambdas

I talked a little about them in a previous post. While a lot (really, a lot) of languages have support for anonymous functions and closures, the “big ones” don’t*. And the way that Ruby implements that is so elegant that most newbies don’t even know they are using a closure, or what would be that.

Actually, C++ (since C++11) and C# (we could use delegates since C# 1.0, but it evolved until C# 3.0) have anonymous functions, and C can do something similar using pointer to functions. Java, on the other hand, doesn’t have anything similar (but everybody is hoping it to implement that on Java 8). But the way Ruby handles that is just so elegant. For example, I can easily select all the non-null entries of a given Array @array with:

non_nil = { |x| x != nil }

2 – Metaprogramming

Check this:

class Numeric
  def method_missing(m)
    time_hash = { "seconds" => 1, "minutes" => 60, "hours" => 3600 }
    if(time_hash.has_key? m.to_s)
      return self * time_hash[m.to_s]

Now I can use the methods “seconds”, “minutes” and “hours” in any numeric object, and with a really DRY code!

These methods are created at run-time, whenever they are needed. Ruby can do that. And it can do more (Rails uses a lot of metaprogramming on ActiveRecord). It’s a really big subject, and I could spend a lot of time talking about that.

3 – Open classes

Have you seen what I’ve done in the previous code? I changed the behavior of the Numeric class. I can do that with any class, have I created it or not. Even built-in classes can have its behavior subscribed.

Now, a lot of people won’t like that, and they have some reasons. And while they can be right sometimes, it is much better to simply change the behavior of a built-in class than to always use a child class on the whole application.

4 – The object model

Everything in Ruby is an object. And when I say everything, that’s everything. Even classes are objects (of the class Class). That means you can create and manipulate almost everything inside of Ruby in runtime.

There are other reasons for why I love Ruby, but these are the main ones.

Ajax on Rails step by step

My previous post about Ajax was aimed to people who knows how to actually make an Ajax solicitation, but this is not the case for people who are beginning. So, I’ll explain better how to do this. I’ll teach it using CoffeeScript and JSON, but you are free to trade technology as much as you want (using Javascript and XML, for example).

What is an Ajax solicitation?

I’m going to be really objective here: an Ajax solicitation happens when you want to request some data from the server (or send it) without reloading the page, and process it with a Javascript callback.

For doing this, you must do three things:

  1. Your server must provide the data via HTTP;
  2. You must make a solicitation;
  3. You must have a callback function for when the solicitation arrives

Provide data via HTTP

That’s really simple. The server does not care if the solicitation is Ajax or not, so every data the server provides you can be retrieved in Ajax. For example, let’s say you have this controller:

class FriendsController < ApplicationController
  def show
    @friend = Friend.find(params[:id])

    respond_to do |format|
      format.json { render json: @friend }

You can retrieve a JSON representation of the friend with id 1 with “GET /friends/1.json”. It doesn’t matter if you requested it from a regular link or an Ajax link, the server will send you the same JSON.

So, it’s really easy on the server side: you can simply remain with your current controllers. At most, add JSON representations to your resources.

Make a solicitation

Generally, an Ajax solicitation is more confuse and obscure. Not on Rails. If you want a link to make an Ajax solicitation, you just have to add the “remote” attribute to it.

For example, if you want to make a link to make an Ajax request from “/friends/1.json”, simply do this:

<%= link_to "Awesome ajax link!", "/friends/1.json", remote: true, id: "ajax_link" %>

And that’s it! You have a Ajax link! It doesn’t do anything yet, but it will on the next step.

I added the “id” to the link so I can pick it easier with jQuery. But you don’t need to, if you want to make it another way.

Make a callback function

Ok, now the “difficult” part. When the response from the solicitation comes, you have to do something with it. But how do you know when the moment came?

You don’t. But the browser does. So tell the browser to call a function when the solicitation comes:

$(document).ready ->
    successCallback = (e, xhr, settings) ->
        myData = jQuery.parseJSON(xhr.responseText)
        # Do whatever you want here. Scramble your DOM, make an alert.
        # Everything you need is in the myData variable
    $('#ajax_link').bind("ajax:success", successCallback)

Ok. That’s not so difficult.

And this is not everything! You can make POST, PUT and DELETE via Ajax, too! Actually, you can do everything! And you do not need to change a lot of things on this tutorial, only how you’ll handle the data you are sending.

Working with lambda functions in Ruby

Ruby provides an easy way of working with closures: the code blocks. Everybody that uses Ruby for a minimum amount of time knows how code blocks work. You can do it this way:

def foo(a)
  # Some code here, create n
  # More code here

# Some code here, create x
foo(x) do |y|
  # Your code block goes here. You can access any variable from previous scope
  # But everything created here is exclusive for this scope

Or like this:

foo(x) { |y| do_stuff_here }

This is a lot similar, but not exactly equal, to what you can do with a functional language (where you can, for example, pass a function as an argument to another). Code blocks are really practical, but they have some limitations:

  1. You can only pass one block per function;
  2. Blocks can’t return anything. If you need the result of an anonymous function, blocks are not what you need. That’s because the return is non-local; that is, the function that is declaring the block will be the one returning.
  3. You can’t pass the same block more than once, because you can’t storing it anywhere.

But there are two other ways of creating anonymous functions in Ruby that addresses some or all of these problems: procs and lambdas.

1. Procs

Actually, I lied. You can store blocks somewhere. And the place is a proc.

Blocks are, actually, a way for creating procs. They are the same type of closure: they have access to the scope that creates them, their return is non-local and they can be passed as a parameter to another function. If you try to call a proc with additional parameters, they will be ignored, just like it would happen on blocks.

Generally, it is better to use a block than a proc, except when you need to pass more than one to a function or when you want to send the same block to two functions.

But how do you use a Proc?

Simple enough:

def receiver_method(parameter)
  y = 5

test_proc = { |x| x * 3 }
puts receiver_method(test_proc)

This will print 15 on the screen.

2. Lambdas

Lambdas are similar to procs, but there are two main differences:

  1.  If you try to pass the wrong number of parameters to a lambda function, it’ll throw an error
  2. Lambdas can return values without affecting the callee

That is, you can create a lambda function like this:

fat = lambda do |x|
  result = 1
  1.upto x do |i|
    result *= i
  return result

And call it wherever you want that it’ll not affect the flow of the code. In this aspect, lambda functions are similar to regular functions.

Beginning in Ruby 1.9, there is a cleaner syntax for creating lambda functions:

square = ->(x) { x * x }

And actually, lambdas are ALSO procs internally. But this doesn’t matter a lot from a pragmatic point of view.

So, that’s it. Whoever likes functional languages, Ruby has the tools for the job.