On Thu, 27 Apr 2006, erichof425 wrote:

> My first ocaml program translates between Arabic and Roman numerals.

> It's a simple small program to help get more familiar with the

> language. If you would like to take a look at it, here it is. Please

> tell me what you think. I'm sure I did some naive newbie things, so

> any constructive criticism would be welcome.

>

> http://rafb.net/paste/results/zmongR17.html

>

> I don't know if this is an acceptable thing to post here, please let

> me know if it's not and I won't do it again.

There are a couple of things that you could do to make your code

reasonably fast. Specifically, you should use associative lists with

moderation, since finding an item requires to scan half of the list on

average.

(* Lists of each Roman digit, its value, and its character representation *)

let digits = [I; V; X; L; C; D; M];;

let values = [1; 5; 10; 50; 100; 500; 1000];;

let chars = ['I'; 'V'; 'X'; 'L'; 'C'; 'D'; 'M'];;

(* Conversions for Roman digits *)

let int_of_roman_digit rd =

let digits_values = List.combine digits values in

List.assoc rd digits_values

;;

The function int_of_roman_digit above is pretty inefficient because (1)

you build a whole list of pairs each time you want to convert a character

and (2) because you use an associative list anyway. Since these lists are

short anyway, it's not crime to use associative lists, but I suggest you

build them once and for all.

You can write directly a list of triplets:

let triplets = [ (I, 1, 'I');

(V, 5, 'V');

... ]

let digits_values = List.map (fun (x, y, _) -> (x, y)) triplets

let int_of_roman_digit rd = List.assoc rd digits_values

For a better efficiency, you can use the Hashtbl module.

With small ints (or chars) as keys, you can even use directly an array,

e.g.

let roman_digits =

let a = Array.make 256 None in

List.iter (fun (x, y, z) -> a.(int_of_char z) <- Some (x, y)) triplets;

a

let find_roman_digit c = roman_digits.(int_of_char c)

Martin

--

Martin Jambon, PhD

http://martin.jambon.free.fr

Edit http://wikiomics.org, bioinformatics wiki