4 module type MATRIX = sig
6 type t = {r : int; k : int}
11 val create : rs:int -> ks:int -> data:'a -> 'a t
13 val get_neighbors : 'a t -> Point.t -> 'a list
15 val map : 'a t -> f:('a -> 'b) -> 'b t
17 val mapi : 'a t -> f:(Point.t -> data:'a -> 'b) -> 'b t
19 val iter : 'a t -> f:(Point.t -> data:'a -> unit) -> unit
21 val print : 'a t -> to_string:('a -> string) -> unit
24 module Matrix : MATRIX = struct
26 type t = {r : int; k : int}
34 module Direction = struct
39 let all = [ NW ; N ; NE
47 | NW -> {r = -1; k = -1}
48 | N -> {r = -1; k = 0}
49 | NE -> {r = -1; k = 1}
50 | W -> {r = 0; k = -1}
52 | SW -> {r = 1; k = -1}
54 | SE -> {r = 1; k = 1}
57 type 'a t = 'a array array
59 let create ~rs ~ks ~data =
60 Array.make_matrix ~dimx:rs ~dimy:ks data
67 f {Point.r; Point.k} ~data
71 let print t ~to_string =
74 Array.iter r ~f:(fun x -> printf "%s" (to_string x));
79 Array.map t ~f:(Array.map ~f:(fun x -> f x))
86 f {Point.r; Point.k} ~data
90 let get t {Point.r; Point.k} =
93 let is_within_bounds t {Point.r; Point.k} =
95 | [||] -> assert false
97 r >= 0 && r < Array.length t &&
98 k >= 0 && k < Array.length t.(0)
100 let neighborhood t point =
101 List.map Direction.all ~f:Direction.to_offset
102 |> List.map ~f:(fun offset_point -> Point.(point + offset_point))
103 |> List.filter ~f:(is_within_bounds t)
105 let get_neighbors t point =
106 List.map (neighborhood t point) ~f:(get t)
110 module type CELL = sig
113 val create : unit -> t
115 val to_string : t -> string
119 val react : t -> states:int list -> t
123 module Conway : CELL = struct
126 let of_int = function
131 let to_int = function
135 let to_string = function
140 Random.int 2 |> of_int
144 let react t ~states =
145 let live_neighbors = List.fold_left states ~init:0 ~f:(+) in
147 | A when live_neighbors < 2 -> D
148 | A when live_neighbors < 4 -> A
149 | A when live_neighbors > 3 -> D
150 | D when live_neighbors = 3 -> A
156 let rec loop bar grid =
158 Matrix.print grid ~to_string:Conway.to_string;
161 Matrix.mapi grid ~f:(fun point ~data:cell ->
162 let neighbors = Matrix.get_neighbors grid point in
163 Conway.react cell ~states:(List.map neighbors ~f:Conway.state)
172 let rs, ks = Or_error.ok_exn Linux_ext.get_terminal_size () in
173 Matrix.create ~rs:(rs - 3) ~ks ~data:()
174 |> Matrix.map ~f:Conway.create
175 |> loop (String.make ks '-')
179 let summary = "Polymorphic Cellular Automata" in
180 let spec = Command.Spec.empty in
181 Command.basic ~summary spec main
184 let () = Command.run spec