
-----------------------------------
Null
Thu Dec 07, 2006 7:42 pm

I'm Learning O'Caml!
-----------------------------------
I'm trying to pick up O'Caml, and I must say, I'm really impressed. 

I like that it's a functional language, with support for imparative and OO programming when needed. 

Some code that I've written in order to teach myself:


(* I'm learning O'Caml!
 *)

let reverse string =
    let rec helper n =
        match n - 1 with
        | -1    -> ""
        | x     -> String.make 1 (string.


type colour =
    | Red
    | Blue
    | Green
    | Yellow
    | Black
    | White;;

class virtual shape ~(colour : colour) =
    object (self)
        method get_colour = colour

        method virtual print : unit
    end

class triangle ~(colour : colour) =
    object (self)
        inherit shape ~colour:colour

        method print = print_endline "Triangle"
    end

class circle ~(colour : colour) ~(radius : float) =
    let pi = 4.0 *. atan 1.0 in
    object (self)
        inherit shape ~colour:colour

        method get_radius = radius

        method area = pi *. radius *. radius

        method print = print_endline "Circle"
    end;;

let main =
    let triangle = new triangle ~colour:Red in
    let circle = new circle ~colour:Blue ~radius:2.4 in

    triangle#print;
    circle#print;

    Printf.printf "%f\n" circle#area;;


-----------------------------------
wtd
Thu Dec 07, 2006 10:20 pm


-----------------------------------
(* I'm learning O'Caml!
 *)

let reverse string =
    let rec helper n =
        match n - 1 with
        | -1    -> ""
        | x     -> String.make 1 (string.[x]) ^ helper x in

    helper (String.length string);;

let main =
    let input = read_line () in
    Printf.printf "%s\n" (reverse input);; 

How about:

let reverse string =
   let sub = String.sub 
   and len = String.length
   in
      match 
         "" -> ""
       | s -> reverse (sub 1 (len s - 1) s) ^ sub 0 1 s

:)

Oh, and I would make this small modification to your classes:

class virtual shape ~(colour : colour) =
    object (self)
        method colour = colour

        method virtual print : unit
    end

-----------------------------------
wtd
Sat Dec 09, 2006 6:51 pm


-----------------------------------
By the way, I think it's fantastic that you're learning O'Caml, and will help out in any way I can.
