4 module type MATRIX = sig
7 val create : rows:int -> cols:int -> data:'a -> 'a t
9 val get : 'a t -> row:int -> col:int -> 'a
11 val set : 'a t -> row:int -> col:int -> data:'a -> unit
13 val map : 'a t -> f:('a -> 'b) -> 'b t
15 val mapi : 'a t -> f:(row:int -> col:int -> data:'a -> 'b) -> 'b t
17 val iter : 'a t -> f:(row:int -> col:int -> data:'a -> unit) -> unit
19 val print : 'a t -> to_string:('a -> string) -> unit
22 module Matrix : MATRIX = struct
23 type 'a t = 'a array array
25 let create ~rows ~cols ~data =
26 Array.make_matrix ~dimx:rows ~dimy:cols data
37 let print t ~to_string =
40 Array.iter row ~f:(fun x -> printf "%s" (to_string x));
45 Array.map t ~f:(Array.map ~f:(fun x -> f x))
59 let set t ~row ~col ~data =
64 module type CELL = sig
69 val to_string : t -> string
73 val react : t -> states:int list -> t
77 module Conway : CELL = struct
89 let to_string = function
94 Random.int 2 |> of_int
99 let live_neighbors = List.fold_left states ~init:0 ~f:(+) in
101 | A when live_neighbors < 2 -> D
102 | A when live_neighbors < 4 -> A
103 | A when live_neighbors > 3 -> D
104 | D when live_neighbors = 3 -> A
110 let main rows cols () =
112 let grid = Matrix.create ~rows ~cols ~data:() |> Matrix.map ~f:Conway.init in
113 Matrix.print grid ~to_string:Conway.to_string
117 let summary = "Polymorphic Cellular Automata" in
119 let open Command.Spec in
121 +> flag "-rows" (optional_with_default 5 int) ~doc:"Height"
122 +> flag "-cols" (optional_with_default 5 int) ~doc:"Width"
124 Command.basic ~summary spec main
127 let () = Command.run spec