Implement a generic matrix abstraction.
[cellular-automata.git] / polymorphic-life / 001 / src / polymorphic_life.ml
CommitLineData
8c93b722
SK
1open Core.Std
2
3
4d49c95e
SK
4module type MATRIX = sig
5 type 'a t
6
7 val create : rows:int -> cols:int -> data:'a -> 'a t
8
9 val get : 'a t -> row:int -> col:int -> 'a
10
11 val set : 'a t -> row:int -> col:int -> data:'a -> unit
12
13 val map : 'a t -> f:(row:int -> col:int -> data:'a -> 'b) -> 'b t
14
15 val iter : 'a t -> f:(row:int -> col:int -> data:'a -> unit) -> unit
16end
17
18module Matrix : MATRIX = struct
19 type 'a t = 'a array array
20
21 let create ~rows ~cols ~data =
22 Array.make_matrix ~dimx:rows ~dimy:cols data
23
24 let iter t ~f =
25 Array.iteri t ~f:(
26 fun row cols ->
27 Array.iteri cols ~f:(
28 fun col data ->
29 f ~row ~col ~data
30 )
31 )
32
33 let map t ~f =
34 Array.mapi t ~f:(
35 fun row cols ->
36 Array.mapi cols ~f:(
37 fun col data ->
38 f ~row ~col ~data
39 )
40 )
41
42 let get t ~row ~col =
43 t.(row).(col)
44
45 let set t ~row ~col ~data =
46 t.(row).(col) <- data
47end
48
49
8c93b722 50let main () =
4d49c95e
SK
51 let pool = Matrix.create ~rows:5 ~cols:5 ~data:() in
52 Matrix.iter pool ~f:(
53 fun ~row ~col ~data:() -> printf "R: %d, K: %d\n" row col
54 )
8c93b722
SK
55
56
57let () = main ()
This page took 0.02066 seconds and 4 git commands to generate.