Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Show comment
Hide comment
@janderit

janderit Jun 17, 2015

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

Owner

janderit commented Jun 17, 2015

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

@SMoni

This comment has been minimized.

Show comment
Hide comment
@SMoni

SMoni Jun 20, 2015

Ruby's still faster ;)

SMoni commented Jun 20, 2015

Ruby's still faster ;)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment