Skip to content

Instantly share code, notes, and snippets.

@awostenberg
Last active February 19, 2021 20:17
Show Gist options
  • Save awostenberg/1fcce76e1d852103e50acd017f621d09 to your computer and use it in GitHub Desktop.
Save awostenberg/1fcce76e1d852103e50acd017f621d09 to your computer and use it in GitHub Desktop.
life
// q: how would you encode Conways rule of life in f#?
// a: how about a pattern match emitting an action?
type Action = NoChange | BecomeInactive | BecomeActive
/// return what should happen to the central cell given active neighbor count
let kernel' centralCell activeNeighbors =
match centralCell, (activeNeighbors<2), (activeNeighbors>3), activeNeighbors=3 with
| true,true,_,_ -> BecomeInactive // living cell with fewer than two neighbors dies
| true,false,false,_ -> NoChange // living cell with two or three neighbors lives to next generation
| true,false,true,_ -> BecomeInactive // living cell with more than there neighbors dies
| false,_,_,true -> BecomeActive // empty cell with exactly three neighbors births new life
| false,_,_,false -> NoChange
@dmadouros
Copy link

dmadouros commented Feb 19, 2021

Cool.

Could you also implement it like so?

match isCentralCellActive, activeNeighbors = 2, activeNeighbors = 3
true, false, false -> BecomeInactive
false, _, true -> BecomeActive
_, _, _ -> NoChange

It's not as explicit with the rules, but it seems easier to understand.

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