Installing Ocaml 4.00 Mac OSX

This is a small guide of how to install OCaml in Mac OSX.

First of all make sure that you have XCode command line tools installed. If you don’t, install XCode, go to Downloads and add the Command-Line Tools.

Now you should download the package from the INRIA website:

(Website)

1) Installation

Mount and install the .pkg

Open the terminal and test the main commands from the OCaml package. (If you want a hint, buy the application Cathode, simulates a much nicer console experience once you modify it for you taste)

Check if exists:
– ocaml
– ocamlc
– ocamlopt
– ocamlrun

(If all is okay proceed, if not try reainstalling it again)

2) IDE’s

There are a lot of diferent IDE’s for OCaml. They exists from very complete to very simple, but, in my humble opinion, there isn’t a dedicated medium IDE.

For large projects -> OCaIDE an Eclipse plugin
For small and medium projects -> Camelia

My choice: Either Emacs with (TypeRex Mode) ou TextMate

1) Install Emacs
2) Download TypeRex (http://www.typerex.org/download.html)
3) Intall with the instruction set on the webstie
4) Ready to go

TextMate
1) Get TextMate
2) Go to the bundles repository (http://netcetera.org/cgi-bin/tmbundles.cgi)
3) Download the OCaml bundle (copy the text to a new text file)
4) Save the file, no extension needed)
5) Execute the file with bash and in SUDO mode
6) Reload Bundles in TextMate
7) Ready to go

Personally, as a Mac user I prefer TextMate, although I still believe Emacs is one of the most powerful editors out there.
I just haven’t worked with TextMate, as long as I have with Emacs.

3) Testing

(In Construction)

Tagged , , ,

Threading with Ocaml

Building, Check writing notes

Tagged , , , , ,

Lexical Tree – The redo Exercises

Ok, so the first code I made for this exercise was bad, and I couldn’t get to the solution, so this is a redo!

 

The exercise is from the O’Reilly book on Ocaml, “Developping Application with Ocaml”.

Its the Second exercise of the second chapter, Lexical Trees.

 

The exercise is simple. A structure for the Lexical Tree is given, and also its nodes, and what is asked is to build the methods to access and modify the tree.

Its functional programming so the point is not to reuse variables but to make copies, I want to keep that in mind this time.

 

As opposed to before, I will first use a pen and papers and then code it in Ocaml.

 

1. Write the function exists which testes wether a word belongs to a dictionary or not, of type lex_tree

Its impossible not to be biased after viewing the solution, so:

1. Pattern match dictionary with 3 cases:

Empty Dictionary

Filled and Letter = word.[i]

Filled and Letter != word [i]

2. Make it recursive, after all its the point of the xercise

Create an auxiliary function that you can call and increment i

3. Everytime you call the function, it only happens in the second case, call it with the substring of word

4. Return the value as boolean

(5. End case of recursion is n = 1!, when the word reaches the last word, return the node boolean)

 

From O’Reilly

# let rec exists w d = 
let aux sw i n = match d with
[] -> false
| (Letter (c,b,l))::t when c=sw.[i] ->
if n = 1 then b else exists (String.sub sw (i+1) (n-1)) l
| (Letter (c,b,l))::t -> exists sw t
in aux w 0 (String.length w) ;;
val exists : string -> lex_tree -> bool = <fun>

 

2. Write function insert element, which should only insert if it doesn’t exist already


Here we use almost the same algorithm as above.

Keeping in mind we have to return the modified dictionary 

 

From O’Reilly

# let rec insert w d = 
let aux sw i n =
if n = 0 then d
else match d with
[] -> [Letter (sw.[i], n = 1, insert (String.sub sw (i+1) (n-1)) [])]
| (Letter(c,b,l))::t when c=sw.[i]->
if n = 1 then (Letter(c,true,l))::t
else Letter(c,b,insert (String.sub sw (i+1) (n-1)) l)::t
| (Letter(c,b,l))::t -> (Letter(c,b,l))::(insert sw t)
in aux w 0 (String.length w) ;;
val insert : string -> lex_tree -> lex_tree = <fun>

 

3. Write a function construct which takes a list of words and constructs the dictionary

Simple as it sounds. With what I learned before, I will create a simple recursive function.

I did a solution of mine, almost similar, but the one in the solutions is far simpler.

 

1. Receives a list of strings and returns a dictionary

2. Create récursive aux fonction, just as done above. 

3. If empty list, its the end so, return dictionary

4. If not empty, call aux recursion with rest of list and new dictionary (returned from insert head dictionary)

5. Done

From O’Reilly

# let construct l = 
let rec aux l d = match l with
[] -> d
| h::t -> aux t (insert h d)
in aux l [] ;;
val construct : string list -> lex_tree = <fun>

 

To continue…


Tagged , ,

PATRIOT : Missile and The Enemy Launcher

I like to program by step, and steps i can verify their results quick and easily. 

I tend to do this more often when I’m not sure this is the way to go, and this is a good example.

I haven’t posted yet, but I will, a small introduction to this project/problem.

This is for a class of Real-Time Systems. i have to build a simulator an anti-missile system. It has to work on threads, communicate by queue, and it should have some real-time properties.

I am doing this in Ocaml because its the language I must learn for my final thesis, therefore its a win win situation I guess.

 

My solution is simple, and real straight forward to implement in a language like C. But in Ocaml there is so much choices and approaches, that I am not still sure was the best way to go.

The solution consist of 3 main Task: The enemy, The World and The PATRIOT system, more detail in my next post.

 

In this first approach I will start by defining my Missile and create a first version of the enemy missile launcher, and also name it! Maybe to Gundam! Or V.A.D.E.R, we will see.

 

Slow Steps

I told you I like slow steps.

 

So my first try will be to make a small module with a method printMissile that simply prints out: “I am Missile nº X”.

 

let print_Missile id =
Printf.printf “I am Missile %d\n” id;;

 

Now, this is done, easy right? Ok, so, let me try putting this on an endless loop and stop when I insert ‘x’.

This was also possible using recursion, but here I preferred to use imperative programming, using references, it is more intuitive for an infinite loop with this purpose.

 

let i = ref 1 in
while !i != 0 do
print_Missile !i;
i := read_int () ;
done ;;

 

I wanted to try and launch a process that would keep updating the value of the string printMissile but seems I can’t compile a program when calling the Unix module.

I will stop this for now, and come back to finish it later.

 

I asked in StackOverflow for some help, because help on this topic seems inexistent. 
I will go back trying to solve the Tree exercises. 

 

(Published 3/12/12)

Edit: 

Problem solved. Seems I had an incomplete installation of Ocaml. Unix module is now working, tested it with .Date function and .Time

Paused this function while I couldn’t solve it and started working on the Graphics interface.

So I will return to this point as soon as possible.

 

(Published 9/12/12)

Edit:

After studying a bit more of Unix and Threads I was able to develop a small program that would launch a missile.

In this example, missile are threads, therefore we can launch as many missiles as we want.

Here is the code:

 

And here is the class module:

 

 

More info on both of these specific subjects can be found in these posts:

 

 

 

Tagged , , , , ,

Compiling and Executing

Well I have been studying Ocaml for some days now but I have been using the Ocaml top-level to test my code until now. 

Therefore, I decided to grab a book and start understanding how to build a small project.

 

ByteCode vs NativeCode

For starters, there are two compilers, one generates portable code and the other one  specific architecture performance programs.

They byteCode compiler, from what I could understand, works like Java Virtual Machine. It is, in fact, a Virtual Machine, its name is Zinc (Zinc is not Caml). The byteCode compiler generates Zinc instructions. 

This way code can be run in any system where a byteCode compiler as been developed for, just like JVM.

The native compiler is optimized for the architecture of the system it was designed for.

ocamlc (ByteCode compiler)

ocamlopt (NativeCode compiler)

 

Compiling

Compiling a single file is as simples as doing it with a C compiler:

ocamlc -o executalbe_file source_file.ml

Its analogous to the native compile. Its quite simple, nothing to add here.

 

Running Toplevel

If you are using, or just started working with, Ocaml, the first thing you notice is that you have a nice little thing called Toplevel execution. If you used MATLAB, like I did, the first thing you will think is: “This is just like MATLAB console”

Basically yes, it runs Ocaml code right on the fly, which is very useful, for debugging or testing.

But, I haven’t studied much about it in particular. I will try to do it later, because it has some interesting directives like #trace.

 

Modules

Now, the reason why I made this little summary, Modules. I need modules, I think everyone needs. 

So, I decided to go a bit back and try to understand how it works, from compiling a simple file to testing it.

I want to make a small project that simulates an Anti-Missil (check project here), and for that I want to use modules.

Modules in Ocaml, so far look like they are the same as in Java or C, you make them in different files (usually) and compile each one individually and compile the interfaces with the main file in the end. 

I will test a small example to see if I am able to do a simple module compile and execution:

I created a small program a.ml that defined a record and a method for this record, and another program b.ml that would create a value of type record A and call the method on it. Therefore b.ml depends on a.ml

Compiling the files according to dependency, first a.ml then b.ml, worked fine.

I guess makefiles will be useful in the future.

For now I will stop my experiments with modules and try to start solving my project: Anti Missile.

 

 

 

This post will be reviewed as soon as I can so it has the correct information. Right now it was written as a form of a work log.

 

Thank you,

João Bastos

  

Tagged , ,

Lexical Trees and the quest for redefining a variable

I have been doing some exercises from the O’reilly book, which by the way is very good, and I always end up failing or missing the point of the exercises.

I discovered that the solutions are available in the online version of the text-book ( who would have guessed?), and since then have been confirming my solutions.

This post is about the Lexical Tree exercise.

My struggle has been to understand reset my mind to think recursively and not imperatively. Its hard. I have been a C, C# and Java programmer as long as I remember. I like recursive functions, but its hard for me to think of them as a first approach.

Anyway, after slowing down and think about all the possible cases and criteria’s I was able to find a suitable solution, however, not as good as the one provided by the authors.

The elegance in Ocaml keep amazing me, its so simple.

The functions are all the same after you know how to go though the tree. That’s the elegance.

I will redo the assignment and post here a good solutions and scheme.

For now I just want to record these thoughts and discoveries:

– Recursive always!
– Use pattern matching when possible, to attend the several constraints and cases
– Use the libraries, String in this specific case
– Practice in paper first!

Doubts:

I still can’t think of a good way of redefining values. The functions return a new data structure, a modified data structure but if I don’t use it again, or recursively I loose the information.

Right now, I am using let for re-assigining the values. for ex:

– let d = insert w d;;
– let d = insert w2 d;;

And so on.

Edit 3/12/12

After sleeping on this, I realized how stupid I was being by trying to force imperative thinking on this language again.

There is no need for mutable variables, here I have to start thinking about returning a new instance.

Its really hard to think like this, I have been completely formatted for imperative programming.

I just got a small new book to take a look, its called “Thinking Ocaml”. I post later a follow-up on this.

 

 

Tagged , , ,