formations/algo/poo/cours/annexes/ojbML.txt

107 lines
4.2 KiB
Plaintext
Raw Permalink Normal View History

Object en ocaml
===============
::
utop # let myPt =
object
val mutable x = 0
val mutable y = 0
method get_x = x
method get_y = y
method setcoord new_x new_y = x <- new_x ; y<- new_y
end;;
val myPt : < get_x : int; get_y : int; setcoord : int -> int -> unit > = <obj> ─( 17:23:21 )─< command 1 >───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────{ counter: 0 }─utop # myPt#get_x ;;
- : int = 0 ─( 17:23:24 )─< command 2 >───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────{ counter: 0 }─utop # myPt#setcoord 5 89 ;;
- : unit = () ─( 17:23:45 )─< command 3 >───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────{ counter: 0 }─utop # myPt#get_y
;;
- : int = 89
classe point
------------
::
(* ocamlg points.cmo pointClass.ml *)
open Graphics ;;
open Points ;;
open_graph " ";;
set_line_width 5 ;;
set_color magenta ;;
set_window_title "points" ;;
let p1 = new point (0,0)
let p2 = new point (3,4) ;;
p1#lineto (10,28) ;;
p1#lineto (222,55) ;;
print_string (p1#to_string ()) ;;
print_newline () ;;
p1#lineto (50, 125) ;;
ignore (read_key () ) ;;
close_graph () ;;
::
(* l'objet point comme la possibilite de lier
la representation et le dessin sur le graphe
*)
(* ocamlc graphics.cma points.ml *)
class point (x_init,y_init) =
object
val mutable x = x_init
val mutable y = y_init
method get_x = x
method get_y = y
method moveto (a,b) = x <- a ; y <- b
method rmoveto (dx,dy) = x <- x + dx ; y <- y + dy
method lineto (a, b) = Graphics.lineto a b ; x <- a ; y <- b
method to_string () =
"( " ^ (string_of_int x) ^ ", " ^ (string_of_int y) ^")"
method distance () = sqrt (float(x*x + y*y))
end ;;
(*
let p1 = new point (0,0)
let p2 = new point (3,4) ;;
p1#get_x;;
p2#get_y;;
p1#to_string();;
p1#moveto (1,2) ;;
p1#rmoveto (2,5) ;;
p1#to_string () ;;
*)
(* point avec un record
type color = Rouge | Vert | Bleu
type point = {x:int; c:color}
class point (x_init, y_init) =
object
val x = x_init
val y = y_init
method get_x = x
method get_y = y
(* a faire avec le self *)
method moveto (point:p) = point(p.get_a,p.get_b)
method rmoveto (point:p) = point(x + dx, y + dy)
method to_string () =
"( " ^ (string_of_int x) ^ ", " ^ (string_of_int y) ^")"
method distance () = sqrt (float(x*x + y*y))
end ;;
let p1 = new point (0, 0);;
let p2 = new point (3, 4);;
(*
p1#get_x;;
p2#get_y;;
p1#to_string();;
*)