Articles Labelled with “Objective Caml”

Installing OCaml Batteries

In this post I want to help OCaml newcomers to install Batteries. The task is trivial under Linux, while it's a bit tricky under Windows, because OCaml still lacks a self-contained Windows installer.

My assumption is that the reader is a coder, so I will not explain everything… Let's start with the easy part: Linux.

Linux

The installation of OCaml + Batteries under a Debian/Ubuntu system couldn't be easier, thanks the the hard work of the Debian OCaml Task Force. So open a terminal and type:

$ sudo aptitude install ocaml-batteries-included

That's all for Debian/Ubuntu. I don't know how Fedora works, but I think it's easy to install Batteries using YUM, something like:

$ yum install ocaml-batteries-included

If a RPM package for Batteries wasn't available, you could still install OCaml, Camomile (the Unicode library), and compile Batteries from sources, as described below for the Windows OS.

Windows

As said, this OS still lacks a self contained installer which is in progress, at least for installing OCaml. Since many OCaml versions are available for Windows, with different pros and cons, I had to decide which one to use, and I decided to follow the simplest path to reach the goal of installing all the stuff we need. The Cygwin port is by far the simplest way.

  1. Download Cygwin setup and double click the executable. In Windows Vista/7 (I made my test on a Windows 7 64bit box) you will be required to allow the program to be run a couple of times, as usual ;-) …
  2. when the list of available packages appears, select: each and every package containing "caml" (see the screenshot below), and also make, m4, libncurses-devel, git, wget and rlwrap;
    Necessary Cygwin packages
  3. open the Cygwin shell;
  4. download the Findlib library, version 1.2.6:
    $ wget http://download.camlcity.org/download/findlib-1.2.6.tar.gz
    
  5. unpack, compile and install Findlib:
    $ tar -xpzf findlib-1.2.6.tar.gz
    $ cd findlib-1.2.6/
    $ ./configure
    $ make
    $ make install
    
  6. download, unpack, compile and install Camomile 0.8.1:
    $ wget http://prdownloads.sourceforge.net/camomile/camomile-0.8.1.tar.bz2
    $ tar -xpjf camomile-0.8.1.tar.bz2
    $ cd camomile-0.8.1/
    $ ./configure
    $ make
    $ make install
    
  7. the last step is to download compile and install Batteries itself. I wasn't able to compile the latest stable release (1.2.2), for an obscure preprocessor error, but using the latest GIT branch everything went smoothly. So here are the steps:
    $ git clone git://github.com/ocaml-batteries-team/batteries-included.git
    $ cd batteries-included/
    $ make camomile82
    $ make all doc
    $ make install install-doc
    

Testing the installation

Before starting to play with the library and the toplevel (the OCaml REPL is called toplevel) let's put into action a couple of helpers.

  1. The OCaml toplevel doesn't support readline. To get this feature back we add an alias to .bashrc. This works in both Linux and Windows:
    alias ocaml='rlwrap -H /home/paolo/.ocaml_history -D 2 -i -s 10000 ocaml'
    
    restart the terminal or load another bash;
  2. we need to load Batteries in the toplevel. This is not strictly necessary, but it helps a lot and the Batteries ASCII logo is wonderful :-). All we need is to create a file named .ocamlinit in the home directory. Open your favorite editor and put this phrases in ~/.ocamlinit:
    let interactive = !Sys.interactive;;
    Sys.interactive := false;; (*Pretend to be in non-interactive mode*)
    #use "topfind";;
    Sys.interactive := interactive;; (*Return to regular interactive mode*)
    
    Toploop.use_silently 
                 Format.err_formatter (Filename.concat (Findlib.package_directory 
                 "batteries") "battop.ml");;
    

If everything went well you can now type ocaml and something like this should appear:

$ ocaml
        Objective Caml version 3.11.2

      _________________________
    [| +   | |   Batteries   - |
     |_____|_|_________________|
      _________________________
     | -  Type '#help;;' | | + |]
     |___________________|_|___|


Loading syntax extensions...
	Camlp4 Parsing version 3.11.2

Conclusions

This (rather boring) post has been devoted to the installation details of Batteries under Windows, where it presents some difficulties for newbies. Next time we will start on exploring the library with simple examples to exploit its strength.

Pearls of OCaml Batteries (1)

OCaml Batteries logo

OCaml is known to be a powerful functional programming language, but one of its presumed weakness is a relatively poor standard library.

By accident, I'm one of the few people on the planet considering this very clean and virtually bug free library a feature and not a bug, but this is only an opinion.

The standard library contains everything you need to build applications and other libraries, but it's essential, forget something like the Python standard library and things like “sending an email in one line of code”. Instead, think of the C standard library (plus some important data structures missing in the libc).

More than two years ago the OCaml community decided to start the development of a library containing all the conveniences that are missing in the standard library. The project is OCaml Batteries Included and I'd like to introduce the reader with a series of posts, aimed to cast a light on various aspects of the library, without pretending to be an exhaustive tutorial.

The posts will be targeted at novice OCaml programmers because I think that an experienced OCaml hacker already uses "Batteries" or, in any case, he understand the library API and doesn't need help from this blog.

Before starting with the (boring) installation details, I want to give you a taste of Batteries, to show how a simple task could be written in a more natural way using Batteries modules, in comparison with a vanilla implementation. Let's take this simple task: we want to read a file by lines and print on the terminal only those lines containing a particular substring.

A simple and actually working solution is proposed by the PLEAC-Objective CAML project, it's the very first example of the file access section. Here is the proposed code:

let () =
  let in_channel = open_in "/usr/local/widgets/data" in
  try
    while true do
      let line = input_line in_channel in
      try
        ignore (Str.search_forward (Str.regexp_string "blue") line 0);
        print_endline line
      with Not_found -> ()
    done
  with End_of_file ->
    close_in in_channel

Now let's rephrase using Batteries:

Enum.iter
  (fun l ->
    if BatString.exists l "blue"
    then print_endline l)
  (open_in "/usr/local/widgets/data" |> BatIO.lines_of)

The result is the same, but the code is much cleaner and far more idiomatic for a functional language.

Next time we will see how to install OCaml and Batteries, under Linux of course, but hopefully even under Windows.

OCaml per programmatori Python

Sorry for English speaking people, but this post makes sense only for Italians, so it's in Italian :-)

Qualche mese fa, precisamente a fine Febbraio, mi è stato chiesto di presentare in un breve workshop il linguaggio Objective Caml che, manco a dirlo, è il mio linguaggio di programmazione preferito. Mi ero riproposto di scrivere qualcosa in merito, ma una serie di problemi me lo ha impedito, così colmo con qualche mese di ritardo la lacuna.

Read more…

Source repository of this blog

Following my previous post, some people asked me to show the source code of this blog, so here it is:
http://github.com/pdonadeo/personal_blog.

A general warning: the project wasn't thought to be published and so the code is a pile of scripts kept together in some way. Many parameters are present in the SQLite DB, but if you want to use the blog, expect to find my name, surname or email in the HTML templates, or even in some .ml files.

Moreover, the source code is not homogeneous and the style changes from module to module, because I changed my way (and skill) of programming in OCaml in time.

In any case, I hope you will find it interesting.

My new blog… in Objective Caml

More than a year ago I decided to dismiss my Wordpress blog, and to write a new one from scratch in OCaml. Unfortunately my spare time for programming projects is getting less and less, so this simple work took a lot of time to reach an usable state.

Read more…

Information technology disgrace

The world of information technology is made by men and, like any other activity in which human beings are involved in, mistakes happens. Sometimes huge mistakes. And huge mistakes turn out into disgraces. One of these disgraces has a name: PHP.

Here is the story: some days ago wordpress.org released the latest version and I decided to upgrade. No db changes, everything seems ok. But, wait a moment… the sidebar is broken! To be honest, the page itself seems to be broken. I did nothing strange. Ok, let’s rationalize this: ssh on the server, cd to the wordpress directory and issue:

$ php index.php
Segmentation fault

What the frack?!? I had no time to investigate more, and I decided to install the most recent working backup (I use GIT to track everything, including db backups) and forgot it for some days. Tonight I decided to solve the problem. I installed everything on my PC and, by hacking the DB, I was able to remove all the sidebar widgets, among which I suspected the guilty should be. Than, from Wordpress admin I added exactly the same widgets, in the very same order and with the same configuration.

Result? No more segfault.

Now, how can a so popular application be so fragile? Are Wordpress guys stupid, or what? No, this time the problem is with the technology. One word suffices: PHP.

Yes, I know, I perfectly know I shouldn’t focus myself on this or that technology, I now Facebook is made with PHP, I know everything, but… as an engineer I simply can’t ignore how poor this language is!

Hey, if I considered the language choice unimportant I should work in the marketing :-)

End of this rant: I started my own blog, I’ll write it in a real programming languages, Objective Caml, I’ll never be rich but at least I’ll never ever spend 3 hours of my life debugging a PHP buggy blog.

Draw something on the screen... and interact with it!

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.

Downloading and compiling

First of all, download the source code or, if you want the latest version, clone my GIT repository:

$ git clone http://www.ex-nunc.org/projects/pdonadeo/cairo_toy.git cairo_toy.git

To compile the program you need:

  • OCaml (I have version 3.10.2, but probably 3.10.0 or 3.10.1 are ok);
  • Lablgtk2, the OCaml binding to GTK2;
  • the OCaml binding to libcairo.

All these packages are available in any recent Linux distribution; on Debian/Ubuntu:

$ aptitude install ocaml liblablgtk2-ocaml-dev libcairo-ocaml-dev

To compile instruct this command inside the program directory:

$ ocamlbuild demo_toy.native

The code

The program is very simple and is essentially derived from Erik's code: the core is the functor Toy_maker.Make which accepts, as input, a module with the following signature INTERACTOR:

module type INTERACTOR =
sig
  type state
  val init_state : state
  val win_title : string
  val init_width : int
  val init_height : int
  val cmd_line_handler : state -> string array -> state
  val keyboard_callback : state -> GdkEvent.Key.t -> state * bool
  val pointer_buttons_callback : state -> GdkEvent.Button.t -> state * bool
  val pointer_motion_callback : state -> GdkEvent.Motion.t -> state * bool
  val pointer_scroll_callback : state -> GdkEvent.Scroll.t -> state * bool
  val repaint : state -> Cairo.t -> int -> int -> state * bool
end

In this module the user must provide a type state, which contains the application state, some initialization values, a command line handler (in case you need) and 4 event handlers for the following events:

  • keyboard;
  • mouse motion;
  • mouse buttons;
  • mouse wheel event (scroll events in GTK).

The user also provides a repaint function, which takes care of repainting the Cairo context.

As a demo I wrote a simple My_interactor module implementing the following simple features:

  • left click on the gray background creates a new circle;
  • left click inside an existing circle moves it around;
  • right click inside a circle deletes it;
  • the mouse wheel zooms (in and out);
  • middle click is used to pan;

Here is the result.

Yes, it's somewhat dull, but it does its job. Have fun!

Copyright © 2004–2012 by .
Creative Commons License Content on this site is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 2.5 Italy License.

RSS Feed. Valid XHTML 1.1. This blog is written in Objective Caml. Design based on the work of Rodrigo Galindez.