Paolo Donadeo — LifeLOG

All about my life, job and thoughts
  • rss
  • Home
  • Blog
  • Contacts
    • GPG public key
    • Alessandro Donadeo — Curriculum Vitæ

Draw something on the screen… and interact with it!

Paolo | 01/09/2008 | 13:30

Summary of the previous episodes: 10 days ago Richard Jones complained about the difficulties to achieve simple tasks (drawing a function graph on the screen) on modern computers with modern programming languages; the day after Erik de Castro Lopo replied with a post in which he used GTK and Cairo (better: the OCaml bindings) to achieve the result to draw a simple function on the screen. Yesterday Matias Giovannini added some pepper to this argument using SDL to draw the Newton fractal.

So, what can be added to all this? With a perfect graphic toy you can draw on a window with simple commands, of course, but you also want to interact with the objects you drew. So I elaborated Erik example to add some keyboard and mouse interaction with the graphics on the screen. Read the rest of this entry »

Comments
2 Comments »
Categories
Article, Computer programming, English, Objective Caml, Spare time
Tags
Article, Computer programming, English, Objective Caml, Spare time
Comments rss Comments rss
Trackback Trackback

Holiday!

Paolo | 05/07/2008 | 22:15

Next week I’ll be away on holiday, finally! It’s only one week, but better than nothing. I’ll be back on line Monday the 14th of July.

Ciao!

Comments
No Comments »
Categories
English, Life, News
Tags
English, Life, News
Comments rss Comments rss
Trackback Trackback

Sending emails via Gmail with Objective Caml

Paolo | 26/04/2008 | 23:00

Gmail logo with the caml

Motivation

Last week I was writing a Python script to make an automatic backup, and I decided to send me an email in case of scp failure. I decided to use Python to send the email, possibly via GMail and I found this interesting blog post: Sending emails via Gmail with Python. I like Python, it’s a good programming language, but my heart (as a developer!) beats for the Objective Caml programming language.

So I decided to port the script presented in the post in OCaml. The result is this sendmail.ml.

Compiling the script

To compile the script you need four software components:

  1. the Objective Caml environment. You can download it from the INRIA site;
  2. Findlib, to make compiling very simple;
  3. Ocamlnet: here is the home page of the project;
  4. OCaml binding to the SSL library.

You can of course compile all this stuff, but every decent Linux distributions has all packaged. In Debian you have to run the following command:

# aptitude install ocaml libocamlnet-ocaml-dev \
  libssl-ocaml-dev ocaml-findlib

Now, to compile the script, issue the command:

$ ocamlfind ocamlopt -linkpkg -package \
  netstring,smtp,ssl,str sendmail.ml -o sendmail

Before using it, remember to customize your name, email address, GMail user and password.

Code comparison

The first difference that jumps out at everyone confronting the two scripts is the number of lines: 41 lines for Python against 163 of my OCaml version. The difference is justified by the fact that the Python standard library comes with an almost full featured SMTP client, with ESMTP and TLS capability. On the other side Objective Caml has a very concise standard library, which includes essential modules and data structures, but no “batteries” are provided out of the box. This is a precise design decision by INRIA and, in some ways, I agree with them. Luckily the OCaml community is a source of excellent libraries and bindings, like Ocamlnet by Gerd Stolpmann and the SSL library binding, written by Samuel Mimram. The first one is in particular the Swiss Army Knife for network oriented battles.

Since the SMTP client provided by Ocamlnet doesn’t include TLS capability I decided to stole the source code and adapt it to my needs, to have a more comfortable and high level interface resembling the one offered by the Python standard library.

So the different length is easily explained: 109 lines of code are devoted to the smtp_client class, and the actual script is 54 lines long.

The forward pipe operator

All Turing complete computer languages are equivalent, but everyone knows this is only the theory and everyone have a programming language of choice. Here are two examples of what you can do in OCaml.

The first is the pipe operator:

?View Code OCAML
let (|>) x f = f x

Here we define a (very common in FP) infix operator which simply inverts the order of its operands. What the frack is this? Very simple, we use it to invert the order of a function with its last parameter so, if we want to compute the 3rd Fibonacci number we can write:

?View Code OCAML
let fib3 = fibonacci 3

but also:

?View Code OCAML
let fib3 = 3 |> fibonacci

This is not a style issue, we can define a simple infix operator that feeds a function with a value; we can of course connect several functions together, like in a shell script with the Unix pipe operator, transforming an ugly and difficult to be read call:

?View Code OCAML
let result = func1(func2 (func3(x)))

into:

?View Code OCAML
let result = x |> func3 |> func2 |> func1

In the sendmail.ml script, line 127, we read:

?View Code OCAML
email_string |>
  Str.global_replace new_line_regexp "\r\n" |>
    Str.split crlf_regexp |>
      List.iter (fun s ->
        self#output_string (if String.length s > 0 && s.[0] = '.' then
                              ("." ^ s ^ "\r\n")
                            else s^"\r\n"));

Here we take the string containing the email, we replace all new lines with the sequence “\r\n”, split the stream into lines and in the end send each line to the SMTP server, taking care of quoting each line starting with a period. In 6 lines of code.

Algebraic data type

Algebraic data type are a very interesting aspect of functional programming. We can easily wrap two heterogeneous data types into a single one with two line of code:

?View Code OCAML
type socket =
  | Unix_socket of Unix.file_descr
  | SSL_socket of Ssl.socket

The smtp_client class contains a reference to the connection handle used for communicating with the server which is a plain file descriptor or an SSL socket, which one depends on the state of the communication. I do not want to create a virtual class or an interface and two implementing class as I should do in horrible languages like Java, spending half an hour deciding which methods to put in the public interface, and so on; after all, it’s only a file descriptor!

Now I have a new type which is a disjoint union of the two original types and I can write code like this (line 54):

?View Code OCAML
let input = match channel with
  | Unix_socket s -> Unix.read s
  | SSL_socket s -> Ssl.read s in

Here we say: if channel is actually a Unix file descriptor, let’s define a new function “input” which is the standard function “read”, from Unix module, otherwise, if channel is an SSL socket, let’s define “input” as the Ssl.read function, which works only in ciphered sockets. From now on I’ll use input instead of one of the two original functions.

Ok, it’s time to stop the waffle. Enjoy the script if you need, it’s completely free, like in free beer, in free speech and even in free sex! :-)

Comments
No Comments »
Categories
Article, Computer programming, English, Objective Caml, Python, Spare time
Tags
Article, Computer programming, English, Objective Caml, Python, Spare time
Comments rss Comments rss
Trackback Trackback

BBC article on Italy and mafia

Paolo | 14/04/2008 | 13:35

BBC logo

Today I read an article on BBS News about Sicily and mafia, signed by Stephanie Holmes. BBC reports a number of associations struggling against Cosa Nostra, and a increasing feeling of freedom among young people living in the South of Italy.

Yesterday and today we are voting for the general election and it’s very remarkable that BBC decided to publish an article with a taste of hope, instead of the usual political analysis that would depress every Italian with an ounce of love for Italy.

Read the article, it’s worth the time it takes.

Comments
No Comments »
Categories
English, Life, Politics, Review
Tags
English, Life, Politics, Review
Comments rss Comments rss
Trackback Trackback

Administration

  • Log in
  • Entries RSS
  • Comments RSS

Search with Google

Facets (like tags, but better)

Article Books Chillout Cinema Computer programming Digital life Editors Essay Information retrieval Job Karate Librarianship Life Linux Music News Nu-jazz Objective Caml Photography Politics Python Random thoughts Review South American literature Spare time Tips Visual arts Writing

Facets hierarchy

Site map

  • Home
  • Blog
  • Contacts
    • GPG public key
    • Alessandro Donadeo — Curriculum Vitæ

RSS Recent links on del.icio.us

  • nautilussvn - Google Code
  • Apache CouchDB: The CouchDB Project
  • Creating a Progress Bar Using CSS and JavaScript
  • MooCrop: Mootools 1.2 Image Cropping
  • OCamlP3l
  • 10 Useful Techniques To Improve Your User Interface Designs
  • on facebook and graphology

RSS Interesting News

  • Putting OCaml's type system to work: Writing statically-checked XML [PDF]programming: what's new online
  • L'inadatto presidenteAntonio Di Pietro
  • Unemployment fears worry GermansBBC News | Europe | World Edition
  • on facebook and graphologyi'm in a hurry - stefano zacchiroli blog
  • Comic for December 14, 2008Dilbert Daily Strip
  • Fast PDF viewing right in your browserGmail Blog
  • Abruzzo: un modello virtuosoAntonio Di Pietro

My Last.Fm

Recent Posts

  • Si riparte…
  • Draw something on the screen… and interact with it!
  • Ascoltare Radio Monte Carlo… con Linux
  • Holiday!
  • Vacanze!
  • Ritardo Cronico
  • PyCon Due

Old posts

  • September 2008 (2)
  • August 2008 (1)
  • July 2008 (2)
  • June 2008 (1)
  • May 2008 (1)
  • April 2008 (2)
  • March 2008 (1)
  • January 2008 (4)
  • November 2007 (2)
  • October 2007 (6)
  • August 2007 (2)

Blogroll

  • Alex
  • Andrea
  • Benji
  • Dome
  • Gigi
  • Ilaria
  • kOoLiNuS’s blog (English)
  • kOoLiNuS’s blog (italian)
  • Le ricette del secco
  • Roberto Gastaldi
  • Tommaso Carullo

Make me a present...

My Amazon.com Wish List
My Hoepli.it Wish List
rss Comments rss valid xhtml 1.1 Viewable With Any Browser design by jide