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:(row:int -> col:int -> data:'a -> 'b) -> 'b t
15 val iter : 'a t -> f:(row:int -> col:int -> data:'a -> unit) -> unit
17 val print : 'a t -> to_string:('a -> string) -> unit
20 module Matrix : MATRIX = struct
21 type 'a t = 'a array array
23 let create ~rows ~cols ~data =
24 Array.make_matrix ~dimx:rows ~dimy:cols data
35 let print t ~to_string =
38 Array.iter row ~f:(fun x -> printf "%s" (to_string x));
54 let set t ~row ~col ~data =
59 module type CELL = sig
64 val to_string : t -> string
68 val react : t -> states:int list -> t
72 module Conway : CELL = struct
84 let to_string = function
89 Random.int 2 |> of_int
94 let live_neighbors = List.fold_left states ~init:0 ~f:(+) in
96 | A when live_neighbors < 2 -> D
97 | A when live_neighbors < 4 -> A
98 | A when live_neighbors > 3 -> D
99 | D when live_neighbors = 3 -> A
105 let main rows cols () =
107 let init ~row:_ ~col:_ ~data = Conway.init data in
108 let grid = Matrix.create ~rows ~cols ~data:() |> Matrix.map ~f:init in
109 Matrix.print grid ~to_string:Conway.to_string
113 let summary = "Polymorphic Cellular Automata" in
115 let open Command.Spec in
117 +> flag "-rows" (optional_with_default 5 int) ~doc:"Height"
118 +> flag "-cols" (optional_with_default 5 int) ~doc:"Width"
120 Command.basic ~summary spec main
123 let () = Command.run spec