From d9fa5d4693dd3d31314cb1fd4f54669a1cbaf6bf Mon Sep 17 00:00:00 2001 From: Siraaj Khandkar Date: Sat, 28 Sep 2013 00:29:54 -0400 Subject: [PATCH] Organize transition mechanism into Automaton module --- polymorphic-life/001/src/polymorphic_life.ml | 58 +++++++++++++------- 1 file changed, 37 insertions(+), 21 deletions(-) diff --git a/polymorphic-life/001/src/polymorphic_life.ml b/polymorphic-life/001/src/polymorphic_life.ml index e08dc2a..5835ff2 100644 --- a/polymorphic-life/001/src/polymorphic_life.ml +++ b/polymorphic-life/001/src/polymorphic_life.ml @@ -153,34 +153,50 @@ module Conway : CELL = struct end -type opt = { interval : Time.Span.t - ; bar : string - } +module Automaton : sig + type t + val create : rows:int -> columns:int -> interval:float -> t -let rec loop opt grid = - print_endline opt.bar; - Matrix.print grid ~to_string:Conway.to_string; - print_endline opt.bar; + val loop : t -> unit +end = struct + type t = { grid : Conway.t Matrix.t + ; interval : Time.Span.t + ; bar : string + } - let grid = - Matrix.mapi grid ~f:(fun point cell -> - let neighbors = Matrix.get_neighbors grid point in - Conway.react cell ~states:(List.map neighbors ~f:Conway.state) - ) - in - Time.pause opt.interval; - loop opt grid + let create ~rows:rs ~columns:ks ~interval = + { grid = Matrix.map ~f:Conway.create (Matrix.create ~rs ~ks ()) + ; interval = Time.Span.of_float interval + ; bar = String.make ks '-' + } + + let print t = + print_endline t.bar; + Matrix.print t.grid ~to_string:Conway.to_string; + print_endline t.bar + + let next t = + let grid = + Matrix.mapi t.grid ~f:( + fun point cell -> + let neighbors = Matrix.get_neighbors t.grid point in + Conway.react cell ~states:(List.map neighbors ~f:Conway.state) + ) + in + {t with grid} + + let rec loop t = + print t; + Time.pause t.interval; + loop (next t) +end let main () = Random.self_init (); - let rs, ks = Or_error.ok_exn Linux_ext.get_terminal_size () in - Matrix.create ~rs:(rs - 3) ~ks () - |> Matrix.map ~f:Conway.create - |> loop { interval = Time.Span.of_float 0.1 - ; bar = String.make ks '-' - } + let rows, columns = Or_error.ok_exn Linux_ext.get_terminal_size () in + Automaton.create ~rows:(rows - 3) ~columns ~interval:0.1 |> Automaton.loop let spec = -- 2.20.1