{{ message }}

Instantly share code, notes, and snippets.

janderit/F# Game of life

Created Jun 17, 2015
Concise F# version of Conway's Game of Life
 (* F# Game of life Philip Jander @ph_j 2015 This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License. https://creativecommons.org/licenses/by-nc-sa/3.0/ *) module GameOfLife = let private rng = new System.Random() let random_cells (rx,ry) number = set [ for x in 1..number -> (rng.Next rx),(rng.Next ry) ] let private printcell (x,y) = if (x>=0 && y>=0 && y<=30 && x<=30) then System.Console.SetCursorPosition(x,y) System.Console.Write("#") let print board = System.Console.Clear() board |> Set.iter printcell let private envelope1 (x,y) = set [ for dx in -1..+1 do for dy in -1..+1 -> (x+dx,y+dy) ] let private envelope = Set.map envelope1 >> Set.unionMany let private active_neighbors cells cell = Set.intersect cells (envelope1 cell) |> Set.remove cell |> Set.count let private cells_with_active_neighbors number active area = area |> Set.filter (fun cell -> (active_neighbors active cell) = number) let step cells = Set.union (cells_with_active_neighbors 2 cells cells) (cells_with_active_neighbors 3 cells (envelope cells)) let rec main board : unit = GameOfLife.print board GameOfLife.step board |> main main (GameOfLife.random_cells (20,20) 50)

janderit commented Jun 17, 2015

 And yes, I know Console.Clear is not great performance. That wasn't the point ;)

SMoni commented Jun 20, 2015

 Ruby's still faster ;)