You are currently browsing the category archive for the 'Programming' category.

A few days ago, I switched to Yellow Dog for my powerbook.
I’m very satisfied with the hardware support. It’s the first distro
that supported my backlit keyboard from the beginning.

However, it lacks a lot of software packages. Most of them can be
taken from Fedora PPC (it’s advised to use those of Fedora Core 5
or). However, other must be compiled.

For example, I had to compile swi-prolog, since the software I’m working
on at the moment is written in Prolog. Swi Prolog itself was easy to install.
I compiled it and I had it working in a few minutes.

However, I was unable to compile XPCE. While I do not use the library itself,
I find it useful sometimes to use gtrace or the ‘graphic’ help.
The problem reported was that Xpm was not found. However, I installed
both libxpm and its development files. The ./configure script reported
that it was not able to link against libXpm.

I first tried manually linking and it worked, so I had a look at the log.
In fact it wasn’t libxpm fault. The test program tried to link both libxpm
and libxt, and the latter failed. Amazingly, the configure script did not
check for errors in linking libxt, so the erroro reported was totally
misleading.
The problem was that there was no libXt.so, but only libXt.so.6. I had to
manually create the symbolic link.

Eventually, I bumped into another error (this time during ‘make’).
The culprit was once again Xt: it seemed that some of its ’standard’ header
files were missing. I found a fedora 5 devel package that fixed that
and I was able to compile xpce.

Quite unfortunately, I can’t use it now. Another bug in the installation of
xorg conjures against me. This bug can be seen using a Tkinter canvas too.
The problem is that ‘names’ of colors are not found (probably because rgb.txt
is in the wrong place). Xpce fails and so does many stuff with Tkinter.

I don’t know where rgb.txt should be. I tried to put it in standard places,
but up to now the server does not find it. The problem is that I have to restart the server each time (and since sometimes this hangs the whole system, I have to reboot, and Red Hat derived distros have slow boots.)

Queste sono le FAQ del newsgroup italiano dedicato a C++.
Mi sono reso conto che in effetti non è facilissimo trovarle,
ache se contengono molte informazioni che risparmierebbero
domande banali sul newsgroup.

Per cui, nel caso, le linko.
Link.

Queste sono le FAQ del newsgroup italiano dedicato a C++.
Mi sono reso conto che in effetti non è facilissimo trovarle,
ache se contengono molte informazioni che risparmierebbero
domande banali sul newsgroup.

Per cui, nel caso, le linko.
Link.



What is a scripting language?

From Wikipedia we read that:

Scripting languages (commonly called scripting programming languages or script languages) are computer programming languages that are typically interpreted and can be typed directly from a keyboard. Thus, scripts are often distinguished from programs, because programs are converted permanently into binary executable files (i.e., zeros and ones) before they are run. Scripts remain in their original form and are interpreted command-by-command each time they are run. Scripts were created to shorten the traditional edit-compile-link-run process.

Of course any self respecting computer scientist knows that definition is meaningless, because a language is a mathematical construct
and is not tied to its implementation. You can write a C interpreter, for example (and there are some). You can also write a compiler for any ‘interpreted language’ (of course the term ‘interpreted language is also meaningless). And there are theoretical constructs (Futamura projections) that given any interpreter are able to build a compiler from it (you could implement them even in practice, though it would be terribly inefficient).

However, any other definition would be misleading as well: if you define a scripting language as a language you can use to “script” (as in “bash script”), then you’ve got definition that’s even more stupid. bash is a scripting language, and so it is Python. However, if someone writes an application that is scripted in C, C becomes a ’scripting language’).

Both definitions have an additional problem: scripting languages are considered somewhat inferior to ‘non-scripting languages’. Some even use the term ‘true programming languages’ (and this ‘true programming languages’ are usually considered to be C and C++, for example).

Lisp, Haskell, OCaml, Prolog

In this dissertation on ’scripting languages’, Lisp is quite emblematic. Lisp can be compiled (there are some Lisp compilers around). But Lisp can also be interpreted. This is one of the most
widespread Lisp environments (and it is an interpreter). Moreover, in Emacs you can just run some Lisp snippets. And Emacs itself is scripted in Lisp (thus Lisp would be a scripting language according to the second definition). However, no one can assert that it is not a ‘true’ programming language. Emacs itself is a beautiful (and complex) piece of software, and a lot of ‘real’ (and extremely difficult) stuff in the AI field has been written in Lisp.

Haskell can be another example. Hugs is an interpreter, ghc is both an interpreter and a compiler. And Haskell is even statically typed (so you see, being dynamic is
not necessary ). The very same applies for OCaml or Prolog. And all this
languages have been used by the most theory-oriented computer scientist to
implement real programs.

I suppose nobody would say that Lisp or Haskell are ’scripting languages’ (even if according to the definitions they are — Haskell is used in many configuration tools by Linspire programmers).

Bash, Perl, Python, Ruby.

All this languages have been labeled as ’scripting languages’. And in fact according to definitions, they are. However, they are very different languages.

Bash is a very simple language designed to do simple things. Unix system administrators used it intensively (along with awk and sed and other utilities) to automate many repetitive tasks. Although this is surely ‘programming’, in some sense it’s different from programming an application from scratch. Some even consider it a ‘lower level’ kind of programming (and surely we must recognize that skills involved in writing a boot script are different from skills used to write a compiler)

Perl was born in this environment: its goal was textual manipulations and interactions between processes in a system. It is a nicer alternative to bash + awk in many situations. Later it has been added a fully fledged object model, but in the while it has been used to write very complex applications that go outside the ‘lower level programming domain’ that is usually associated with ’scripting’. Even though I don’t like Perl anymore, it is a general purpose language, with the same dignity of C or C++.

The ’scripting language’ monicker is not fitting anymore. And it is even less fitting for Python. Python has been an object oriented programming language from the beginning. Good software engineering practices have always been employed. However, many consider it just another scripting language. And of course Python makes a great scripting language.

The domains in which Python excels are the same in which Java is used, for example. However, Python can be used for scripting, too. That is to say… some (and I’d be tempted to say ‘most’ ) ’scripting languages’ can be used both as general purpose languages and automation/scripting.

The reason why they can be used for automation/scripting and that they are easier to use and we can write programs faster. The development cycle is faster, too. And to me, they all seem good properties.

I think that the very same features that make Python (or Ruby) great for scripting, make it even greater for general purpose programming. That is to say we should consider a ’scripting language’ not a poorer language, but a better one (yeah, of course this is exaggerated, since there are languages suited for scripting that are not suited for general purpose programming — AppleScript and bash, for example).

I usually call one single emacs server (I’ve got (server-start) at the very beginning of my .emacs), then connect to it with some emacsclient.

Unfortunately enough emacsclient just quits if there is no active emacs server.

I need a process that tries to run emacsclient: if there is no active server, it runs emacs.
Moreover, emacsclient has a -n switch that makes it return ASAP, so the terminal is available for more commands.
emacs has not such a switch, but that behaviour is the one I want.

So I decided to write a small ruby script that does just this:

  1. Tries to run emacsclient with the -n option.
  2. If it succeeds, we are done. Otherwise we run Emacs doing some
    standard posix process manipulation in order to return to the shell as soon as possible.

This is the script:

#!/usr/bin/env ruby

fork do
  exec('emacsclient', '-n', *$*)
end
Process.wait
if $?.exitstatus != 0
  fork do
    Process.setsid
    Signal.trap('HUP', 'SIG_IGN')
    exec('emacs', *$*) if fork.nil?
    exit!(0)
  end
  Process.wait
end

I recently bought the Ruby Cookbook. I bought the italian version (whose title is ‘Ruby Cookbook con elementi di Rails’ which roughly translates to ‘Ruby Cookbook with elements of Rails’). However, the book itself is not different.

Although I prefer to read technical books in English, I often buy books in Italian in order to show the publisher interest on that particular technology. In fact, in a country where most people avoid buying book in English because they feel they are ‘too’ difficult (like in Italy), good technologies do not spread if there are no good books in the local language.

The first impression with the book has been terribly negative. Actually if instead of buying the book online, I found it in a shop and leafed through it, I suppose I would have put it down.

Strings in Ruby are much like strings in other dynamic languages like Perl, Python
and PHP. They’re not too much different from strings in Java and C. Ruby strings are dynamic, mutable, and flexible.

In this paragraph you learn that “Ruby strings are dynamic, mutable, and flexible.” And that is true. However, you get another impression: the authors do not know what they are talking about.

They say that Ruby strings are ‘much like’ the strings in Perl. This is almost true (well, Perl unicode support is much better than Ruby, and Perl deals natively with unicode strings. However, saying that Ruby strings are like Python strings is plainly wrong: Python strings are immutable and are somewhat more akin to Ruby symbols (in fact if you call intern on a Python string you get something semantically very similar to a Ruby symbol). Moreover, Python deals with unicode natively.

Again, the comparison with Java strings is plainly wrong: in Java strings are immutable. The comparison with C is terrible: in C, strings are not even a primitive data type.

As I said before, at this point I was tempted to put the book on a shelf and never open it again. Luckily enough I went on and soon enough I found out I bought one of the best books on Ruby available.

The impression that the authors are not competent (or at least they speak of something they do not know) is plainly wrong. A few chapters later, there are some chapters that quite accurately confront Ruby pragmatic with Python one. They are poignant and precise: definitely the authors know both languages quite well. I suppose the ‘bad’ paragraph at the beginning was a tentative to be didactical.

The book in fact is quite didactical. You can read it with almost no previous knowledge of Ruby. The reader is guided through Ruby syntactical conventions (for example when dealing with strings, you learn that parentheses are optional, which is known to everybody who coded a bit in Ruby).

In the later chapters (most notably the ones on modules and objects), the reader learns the nature of Ruby power, and how to reason and develop in order to unleash that power. This book is a cookbook, but every single receipt does more than teaching a way to achieve its goal: it teaches something about the way Ruby programmers should think and code *in general*. In fact you can consider this cookbook a ‘beginner’ book that teaches by examples (and that is a very effective way in a language such as Ruby). Of course, there is also plenty of intermediate and advanced stuff, or subjects not covered elsewhere (for example the ones about image manipulation).

This is a precious book and the ideal companion for everyone who’s seriously motivated in learning Ruby. But it is also a book that a Ruby programmer may want to keep on her desk to find out how to do things without reinventing the wheel.

Introduction

Ruby is the new boy in town. Until a couple of years ago, nobody really
spoke about Ruby. It was really popular in Japan, but outside it was just
one of the many ’scripting’ languages that the open source world has
developed over the years.

The big names were using Python or Perl. Well, most of them were using PHP,
but in fact this does not matter: while Perl, Python and Ruby are excellent
languages (even if it is almost impossible someone really likes both Perl
and Python, nonetheless Perl has its merits), PHP plainly sucks.
And then of course
there was that Java everybody was talking about and C# (but the open source
guys usually said positive things about it only if in the same sentence
the word ‘mono’ occurred).

In the last few years Rails changed things. Now a lot of people are talking
about Ruby and dynamic languages. A lot of Java developers discovered the
power of dynamic languages and dynamic typing, after years spent saying
that the only saviour was static typing. In fact it seems to me that there
is kind of a revolution in the IT world.

Python and Ruby and Lisp and …

Rails is a pretty good framework. The documentation is acceptable even for
those who grew up with Sun’s bloated documentation (I still prefer to read
the code if the language itself is readable enough).

Ruby is a really nice language. In fact you can see it as a (Perl–)++.
It kept almost all nice features from Perl, and dropped some of the worse.
Of course a Perl Monger would disagree, but I’m a pythonist after all.

One of the most interesting things, in my opinion, is that Ruby and Python
are quite similar (even if they start from different points of view). I feel
quite comfortable with both languages, and even their pragmatic is not
really
different. Moreover differences tend to depend on different
syntax, rather than on different semantics.

For example in Ruby is quite frequent to ‘open’ classes and add methods.
This is something you can do in Python, even if there isn’t a special
syntax.

>> class A(object): pass
  >> a = A()
  >> a.foo()
  Traceback (most recent call last)
  ...
  <type 'exceptions.AttributeError'>: 'A' object has no attribute 'foo'
  >> def ext_foo(self): print 'foo'
  >> A.foo = ext_foo
  >> a.foo()
  foo

Of course this is far less elegant, and that’s way it’s something less
frequently done in Python.

Ruby has another ‘advantage’ over Python. It’s syntax is less rigid,
and in fact the most typical thing that is in Ruby pragmatic is to
write a DSL in the language itself and program in that DSL.

There are a lot of examples of this strategy in Rails itself. However, this
approach is not new at all. Lisp programmers have been using it since the
beginning, that is to say it’s almost forty years they code DLS in Lisp and
use them to write the application.

Duck typing vs. duck hyping.

Unfortunately I hear people saying quite often that ‘Ruby invented duck typing’. People that just
discovered Ruby, seem quite certain about it. Some of them even told me that
in Python you ‘were not really duck typing’ and that it was something
peculiar to Ruby. But let’s look at the definition (from Wikipedia):

Duck typing is a form of dynamic typing in which a variable’s value itself implicitly determines what the variable can do. This implies that an object is interchangeable with any other object that implements the same interface, regardless of whether the objects have a related inheritance hierarchy. Duck typing is a feature of programming languages such as Smalltalk, Python, Ruby, and ColdFusion.

Of course this is something that you can do in Python. And you can also do it in Objective C, by the way. And in Python it is something plainly obvious, too. Everybody does it, everybody likes it. But nobody thought about using a fancy name when describing the practice in books and blogs.

Amazingly, the term ‘duck typing’ (that some think it’s a Ruby peculiar feature) was probably used for the first time by Alex Martelli when speaking about Python typing system. It was Jul 26 2000, and the english language Ruby newsgroup had been active since the first days of may. There was a mailing list of course, but nonetheless Ruby was relatively unknown outside Japan.

In other words, don’t check whether it IS-a duck: check
whether it QUACKS-like-a duck, WALKS-like-a duck,
etc, etc, depending on exactly what subset of duck-like
behaviour you need to play your language-games with. If
the argument fails this specific-ducklyhood-subset-test, then
you can shrug, ask “why a duck?” (at least, you can if you’re
a Marx Brothers fan and have memorized “Cocoanuts”‘ script;
Monty Python one-true-wayists will have to find their own
simile here), and move on to the next set of tests (why-a-no-
chicken immediately comes to mind, but then one would have
to ask why it crosses the road, so I think we’d better snip it).

Alex’s original post

That is the reason why I say that Ruby supports ‘duck hyping’. Ruby is a very good language. I suppose that if I learnt Ruby before Python, I’d probably like Ruby more than Python (because the languages are quite equivalent, it’s my head that now works in a somewhat more pythonic way). However, there are a lot of people that are really *good* at selling Ruby. An excellent publisher based his early success on Ruby books, the creator of Rails has lots of marketing skills, and so on.

However, I was wondering: why Ruby and not Python? I don’t believe in fortune. To discover the answer (that in this particular case I guarantee it’ s not 42) we must analyze in which ways syntactical features of Ruby (since semantically they are quite interchangeable) influence the language pragmatic, and in which ways the pragmatic contributed to build Ruby success.

And when we are into pragmatic, we are not in the world of the compiler: we are in the world of the programmers. That is to say: we must understand why Ruby has appeal even where Python has not. We must understand in which way the language influenced the way of thinking of so many people, and why Python did not.

In Python Metaclasses are considered an advanced and difficult to use technique. This is certainly true. Developers of ‘production code’ are often discouraged to use metaclasses, since code that makes use of metaclasses is often overly complex (especially for people who are not used to metaclasses).

A further reason to avoid metaclasses is that they truly can be avoided. They do not add much power to Python. However, there are cases when they make ‘client’ code more readable.

Consider this situation: we have a finite set of strings that are used as dictionary keys in several parts of our application. Of course, we don’t want to use explicit strings in every point where they are needed. This is too error prone and bugs are more difficult to track.

A good solution is to put all the strings in a module. We will have code such as

  FOO1 = 'foo1'
  FOO2 = 'foo2'

Good. However, we may want to loop over the constants. One of the more pythonic solutions is this one:

targets = {
    SEARCH        : search    ,
    INFO          : info      ,
    VARIANTS      : variants  ,
    DEPS          : deps      ,
    DEPENDENTS    : dependents,
    INSTALL       : install   ,
    UNINSTALL     : uninstall ,
    ACTIVATE      : activate  ,
    DEACTIVATE    : deactivate,
    INSTALLED     : installed ,
    LOCATION      : location  ,
    CONTENTS      : contents  ,
    PROVIDES      : provides  ,
    SYNC          : sync      ,
    OUTDATED      : outdated  ,
    UPGRADE       : upgrade   ,
    CLEAN         : clean     ,
    ECHO          : echo      ,
    LIST          : list      ,
    VERSION       : version   ,
    SELFUPDATE    : selfupdate,
    HELP          : help
}

locals().update(targets)

In this way we can do whatever we want. However, we could use a class instead of a module. We simply define the constants as class variables. Then we can easily use the locals built-in to create the array of constants. But with a little metaclass trick, we can write more interesting client code.

We could for example write things like:

        for k in PackageKey:
            # do something

or

        if key in PackageKey:
            return self.foo(key)

We can use metaclasses to define a class object that behaves in the way above.

class _ConstantNamespace(type):
    def __iter__(cls):
        for v in cls.keys:
            yield v

class PackageKey(object):
    __metaclass__ = _ConstantNamespace

    NAME                   = name
    VERSION                = version
    REVISION               = revision
    DIRECTORY              = directory
    VARIANTS               = variants
    HOMEPAGE               = homepage
    DESCRIPTION            = description
    BUILD_DEPENDENCIES     = build_dependencies
    LIBRARY_DEPENDENCIES   = library_dependencies
    RUNTIME_DEPENDENCIES   = runtime_dependencies
    PLATFORMS              = platforms
    MAINTAINERS            = maintainers
    keys = [ locals()[key] for key in locals().keys()
             if key.upper() == key and (key.isalpha() or key.endswith(_DEPENDENCIES))]

Concurrency in Java is complex to use and expensive in computational resources. Because of these difficulties, Java-taught programmers conclude that concurrency is a fundamentally complex and expensive concept. Program specifications are designed around the difficulties, often in a contorted way. Biut these difficulties are not fundamental at all. There are forms of concurrency that are quite useful and yet as easy to program as sequential programs (e.g., stream programming as exemplified by Unix pipes). Furthermore, it is possible to implement threads, the basic unit of concurrency, almost as cheaply as procedure calls. If the programmer were taught about concurrency in the correct way, then he or she would be able to specify for and program in system without concurrency restrictions (including improved versions of Java). (Concepts, Techniques and Models of Computer Programming, Peter Van Roy and Seif Haridi)

First of all, I completely agree with the authors. I like learning new languages/paradigms/models and find quite restricting sticking to just One Language, One Platform, One Model. I’m fond of Python (but indeed Python is an excellent imperative/object oriented language that allows functional programming — and logic programming is experimented among other things in pypy). I also like Ruby (again Imperative with functional capabilities). I recently discovered the power of Prolog, and I love Haskell (although I never wrote any substantial piece of software in Haskell).

I can’t imagine working with Java and only with Java (and the same applies to ‘C++ and only C++’ or whatever). However, there is plenty of programmers out there that chose One Language, One Platform, One Model and stick with it. I’m wondering if we can generalize Dijkstra statement

The use of COBOL cripples the mind; its teaching should, therefore, be regarded as a criminal offence.

In fact it seems that Java has the very same problem. A lot of Java programmers are only able to formulate problems (and solve them) thinking in Java. One may argue that maybe business programmers already had their mind crippled, but I don’t think this is the case.

I’m afraid to say the problem is not limited to Java, of course (it’s just more evident because there a lot of Java programmers). There are a lot of excellent C++ (for example) programmers that simply do not believe that large programs written in dynamically typed languages can work (and of course they are wrong, since we can exhibit such programs). On the other hand some Python/Ruby/etc advocates think that static typing is fundamentally bad. In fact it is not: Java type-system is poorly designed. It’s not that static typing is wrong or clumsy. Haskell and OCaml are statically typed, but types do not get in the way: they are a concrete help for the programmer (but this does not imply that a language should be statically typed).

My opinion is that more programming languages, models, paradigms should be taught to programmers. For two main reasons: first, they know more ways to solve a problem and hopefully they will be able to choose the best one; second, they will be able to adapt concepts coming from other models/paradigms/languages to the language they are currently using, thus making the design more elegant.

Elegance is not a dispensable luxury but a quality that decides between success and failure. (Dijkstra)

This article won’t be very interesting for people living in an English speaking country: most technology books are written in (or at least translated to) English. However, things change if you do live in a country where English is not the main language (like Italy) and most people can’t read English comfortably (again, like Italy).

A lot of people working in the IT field here find it more difficult to read in English than in Italian, and they choose books translated in Italian, if they are available.

I prefer English books: they usually cost less and there are no translation errors (by definition). Moreover, there are less errors in general, since more people read the book (and thus has the opportunity to find and report errors). Famous hackers and scientists from all the world usually speak English (and deliver lectures in English): they also tend to write books in English (even if it is not their main language).

Moreover, there are subjects where the translated books (for example Python books in Italy) are *not* the ‘best’ books on the subject. For example in Italy you can buy ‘Programmare in Python’ (that is the translation of Learning Python) or the *very* old ‘Python 2.1 Tutto ed oltre’ (that refers to Python 2.1 and is still being sold). Python in a Nutshell (whose author *is* Italian) is not available, and the list of ‘missing’ titles is much longer.

In a country like Italy, availability of books on a particular technology can be one of the main reasons why that technology is adopted. In fact a lot of Microsoft books (or books on Microsoft products) are translated (or even written from scratch in Italian by Italians). Another language that fills whole bookcases in our bookshops is Java. PHP has a lot of beginners books, too.

In my opinion none of the aforementioned programming environments excels. Java has a beautiful library (although terribly over-engineered) and a very promising VM, but the language itself sucks. PHP has a horrible library, a terrible Virtual Machine and the language itself sucks even more. .Net has a wonderful VM (but unfortunately not cross-platform — a part from Mono), but C# is not better than Java, and VB… luckily enough you can run a recent Python version in the .Net environment, but again, you don’t find a lot (if any) of information about this in Italian books.

Every time a new programmer goes to a bookshop to buy a book to start learning programming, he is very likely to find a book on Java/MS/PHP. And until he ‘grows’ up, and learns to look for pieces of information in other places, he will be bound to those technologies. In fact she could have learned sooner (and having more fun) if she discovered Rails (for Web development) or Python. There *are* some books on those subjects (and a whole free book — but in English — on Django (a Python Rails-like framework), however, they are a few, and someone who starts looks for ‘big names’.

I’s a couple of day I’m hacking with xmodmap and keycodes to make my keyboard behave as I expect.
Recently it sprang to my mind that with SuSE 7.1 I used a utility called xkeycaps.

Unfortunately enough xkeycaps generates an .Xmodmap with keycodes expressed as hex numbers, while xev shows code as decimal numbers

This simple ruby oneliner converts an .Xmodmap file with hex codes to one with decimal codes

cat .Xmodmap.hex |
ruby -n -e "if $_ =~ /keycode\s*(0x[A-F0-9][A-F0-9])\s*=\s*(.+?)\n/; puts \”keycode #{$1.hex} = #{$2} \” else puts $_ end”>
.Xmodmap.dec

provided you called the hex .Xmodmap ‘.Xmodmap.hex’.

Suppose we have an XML parser that converts an XML file into a Prolog term.
We may (quite) easily build one with DCG. I will be doing one soon, for values of ’soon’ that depend on the status of my thesis.
We describe the way the prolog term is built:

Text is simply a prolog term. In a less naive implementation we may want to use the string datatype. However, to show the power of a declarative approach, things would not change a lot. Moreover, if we are using swi-prolog (a widespread open source implementation) internally itis able to use UCS (that is a superset of 16 bit Unicode). We only have to make the parser smart enough to convert entities in the right Unicode character and the whole thing will behave correctly

Attributes are represented as key:value terms, where : is a binary infix functor. Again, this is quite a natural representation.

A tag is represented like an tag(Attributes, Children) term, where term is the name of the tag, andl Attributes and Children are (possibly empty) lists of attributes and ‘children’. This representation is not very clever. In fact you can have more optimized programs representing tags like element(tag, Attributes, Children). That is the way things are done in SWI-Prolog official SGML/XML parser library, but this is a simple example.
A ‘child’ is either a tag or a text section.

This (informal) description can be translated in a straightforward manner in a prolog program. The last thing before presenting the source is an example term representing a very simple XHTML file.

html([], [head([], ['']), body([], [p([], ['ciao ciao', img([src:'ciao.jpg'], [])]) ])])

And now the (81 lines long) prolog source code. You can call it with pp_tag(Term), where Term is the term representing the XML file.

pp_tag(Tag) :-
	!,
	pp_tag(Tag, 0).

pp_tag(Tag, N) :-
	Tag =.. [Tag_Name, Attributes, []],
	!,
	s(N),
	write(’<'),
	write(Tag_Name),
	pp_attributes(Attributes),
	write(' />‘).
pp_tag(Tag, N) :-
	Tag =.. [Tag_Name, Attributes, Children],
	!,
	s(N),
	write(’<'),
	write(Tag_Name),
	pp_attributes(Attributes),
	write('>‘),
	N1 is N+1,
	pp_children(Children, N1),
	nl,
	tab(N),
	write(’‘).

pp_text(Text, N) :-
	name(Text, Chars),
	pp_lines(Chars, N).

pp_line(Line, N) :-
	name(Atom_Line, Line),
	s(N),
	write(Atom_Line).
pp_lines(Lines, N) :-
	((append(Line, [10|Rest], Lines), !),
	    pp_line(Line, N),
	    pp_lines(Rest, N)
	;
	    Line = Lines,
	    pp_line(Line, N)
	).

pp_children([], _N) :-
	!.
pp_children([X|Xs], N) :-
	!,
	pp_child(X, N),
	pp_children(Xs, N).

pp_child(Child, N) :-
	pp_tag(Child, N)
	;
	pp_text(Child, N).

pp_attribute(Name:Value) :-
	!,
	write(Name),
	write(’='),
	pp_quoted(Value).

pp_attributes([]) :-
	!.
pp_attributes([X|Xs]) :-
	write(’ ‘),
	pp_attribute(X),
	pp_attributes(Xs).

pp_quoted(Term) :-
	!,
	write(’”‘),
	write(Term),
	write(’”‘).

s(0) :-
	!.
s(N) :-
	nl,
	tab(N).

Of course this is a ‘toy’ implementation. You find the real thing here.

Front cover of the book

A couple of days ago it arrived my own copy of “Compilers: Principles, Techniques & Tool” by Aho, Lam, Sethi and Ullman, better known as the “Dragonbook” (look at the cover to understand why). This weekend I am starting reading the 992 page long book. Actually I find it well written and very clear, even though I’m at the beginning of the book.

I suspect things will get more complicated while proceeding further. However, I find the subject dramatically interesting. I hope to find enough time to read it quickly and eventually start implementing something. Some ideas contained in the book I suppose will be of great help for my thesis (in fact I’m implementing something that is closely related to a compiler).

Today, while checking my gmail account I read an ad about Servoy being an alternative to Ruby and Rails

Actually, I wanted to check out what was that. I thought about some crappy PHP framework that pretended to do what Rails just cloning its structure, but without Ruby power

In the homepage the first thing you learn about Servoy is that Ruby syntax is complex and that Rails has limited capabilities. Further analisys makes me think it’s a Java based environment scripted in Javascript. Basically they are asserting that Javascript syntax is clearer than Ruby one (which is debatable) and that a RAD like thing built on Java is less limited than Rails. Note that Servoy is not Java: it is something built on Java (so I don’t expect it to be as powerful as Java, or it would be as complex as well).
I’m not against RAD or ‘easy’ environments. I just find ridiculous when they say that Rails is limited (that is false) and that a closed component system is more complete.

Moreover, I don’t know anyone using this Servoy. I haven’t read about it on tech magazines, my fellow developers haven’t heard about it either. My opinion is that it’s a small environment tool that uses Rails popularity (as a comparison) to convince people to pay them for something they could have done easier in Rails.

The same conclusions have been made by this blogger

This is are some (simple) exercises in Prolog using difference lists.
They should be correct, but I have to say I’m a beginning Prolog programmer… so…

inorder_dl(tree(X, L, R), Xs-Ys) :-
	inorder_dl(L, Xs-[X|Zs]),
	inorder_dl(R, Zs-Ys).
inorder_dl(void, Xs-Xs).

preorder_dl(tree(X, L, R), [X|Xs]-Ys) :-
	preorder_dl(L, Xs-Zs),
	preorder_dl(R, Zs-Ys).
preorder_dl(void, Xs-Xs).

postorder_dl(tree(X, L, R), Xs-Zs) :-
	postorder_dl(R, Ys-[X|Zs]),
	postorder_dl(L, Xs-Ys).
postorder_dl(void, Xs-Xs).

Well…. I just discovered this new wonderful world. I really like them a lot.

I suspect I’m getting a little bit more into Prolog programming. However, I still find more exciting Haskell lazy programming. But I have to admit that my scarce love for Prolog it’s more a problem of (my) ignorance.

A couple of days ago my Programming Language teacher built under my eyes a small compiler and and interpreter for arithmetic expressions in less than 10 minutes (while explaining Prolog to my fellow students). In fact he used extensively Prolog unification mechanism (since the arithmetic expressions he was compiling were also Prolog terms).

However, thanks to DCG grammars building a parser is also quite easy.

In fact I’m falling in love with declarative programming. I definitely start liking declarative languages like Haskell (functional) or Prolog (logic) a lot more than classical programming languages.

In fact I still love Python and Ruby. I like C (and  we *need* C). I also like compiled languages like ObjectiveC (waiting for Objective C 2.0…) and D. After all, I like C++ too. But what is the point of Java? I definitely don’t understand. It’s dramatically uninteresting.

I develop a lot on unix remote machines. I have CVS/SVN accounts and shell access. In fact it’s quite tedious to retype the password everytime.

For this reason I started using ssh keys to automate this project. You find a lot of tutorials and informations on this subject, I won’t spend more time on this. Basically you have to generate the key and then you have to upload it with scp or similar on the remote machine. However, I find scp syntax quite boring to type… :P

There is a nifty script that does the job for you. You call something like (with you correct remote credentials), it asks you password and you’re done.

     ssh-copy-id -i ~/.ssh/id_rsa.pub rik0@shell.berlios.de

This script is not in my open-ssh distribution and I had to find it on CVS. The direct download is . However, the script may be upgraded. So if you read this post after some time it has been posted, you may want to find a newer version.

In some sense I’ve always done agile programming. I’ve been in the Python community for a while, and a lot of agile practices are very common. I’ve done a lot unit testing (even if not really before coding but just afterwards) since the very first years as a developer.

In fact, it was even before my Cocoa and ObjectiveC studies that I learnt about patterns and how to use them. In fact patterns are well known in the ObjectiveC community even among newbie programmers, for exampl Anguish, Buck and Yacktman describes Cocoa showing which patterns are used in the framework and how their names differ from the classical GOF ones.

Of course this is not enough to say “Agile Development”: I only had some practices in common with some (most) agile developement methods. I also find quite natural to use tests and code to learn instead of documentation (that is quite common for a lot of open source libraries). What I missed was a theoretical mind-framework.

In some software engineering courses I was introduced to UP. And in fact I could not believe that some people are convinced that it could work well (I agree that you may make it work, however, I think it’s a suboptimal way to develop). It is like freezing insects in order to take pictures of them. While frozen, they stand still and are easier to photograph: however, if you want to photograph insects in the wild this just doesn’t happen to work.

Some of my concerns were also due to Java and to the quantity of code that is not part of the problem but needs to be written for the way Java works. Python leans quite naturally towards agility: the way components interact, the way you can change things and refactor (even without complex refactoring tools like Eclipse).

After some time I discovered Ruby and got in touch with the Ruby community and all the hype about agile programming.

Eventually, I decided to buy Kent Beck’s book on Extreme Programming. However, I wanted a technical book about agile programming. I bought Martin’s Agile Software Development

I love them both and I will talk about Beck’s book another time.

Agile Software Development is a very interesting book. There is plenty of information on agile techniques, and even if you are not a Java developer (which in some sense is my case, since I rarely work in Java) there are lots of interesting stuff.

You learn how to use test driven development and to think using TDD (there is a big difference between writing tests and thinking in a ‘test oriented way’). You learn how to design interfaces while writing tests, and there are examples on software evolution driven by tests.

You definitely have to read the sources (that are really readable and easy to understand): while the explanation is great, the sources would be enough by themselves.

The book also offers a clear explanation of classical principles of object oriented software design (OCP, SRP, LSP, DIP) and packaging (ADP, SDP, SAP). So, you may want to buy this book even if you are not into agile programming and are only interested in a book about Object Oriented software development.

This is a hint abount implementing closures in Java. Of course, if you want to do it in an acceptable way, you would create a custom interface that Does The Right Thing™, something like (semi pseudocode)

interface Closure {
public Object foo(Object bar);
}

However, you can get some ideas from the sequent code

public class StateModifier extends Object
{
protected String x ;

    public StateModifier () {
x = foo;
}

    public Thread getThread(){
final String y = yy;

Thread t = new Thread(){
            public void run(){
x = boo + y;
}
};

return t;
}

    public static void main(String[] args) {
StateModifier sm = new StateModifier();
Thread t1 = sm.getThread();

System.out.println(sm.x);
t1.start();
try {
t1.join();
} catch (Exception e){
//        }

System.out.println(sm.x);

System.exit(0);
}
}

This nice sty comes from an example I found on the web. The code is not mine. However, I wasn’t able to find again the original code (and the original author) to give credit. There may be some small modifications I made: if it does not work, it’s likely it’s my fault.

You can define things like

  \usepackage{niceboxes}
  \newenvironment{definition}[1][Definition]{
  \par
  \SpecialEnv{#1}{LightSlateGrey}{Lavender}{LightSlateGrey}{}%
  }{%
  \endSpecialEnv
  }

Of course you need to have imported xcolors if you want to call colors by name (like LightSlateGrey)

And eventually from Amazon arrived the Latex Companion