Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Functional Refactor #3

Open
wants to merge 11 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,6 @@ obj/
/packages/
riderModule.iml
/_ReSharper.Caches/
.idea
.idea
.ionide
.fake
2 changes: 1 addition & 1 deletion GameOfLife.sln
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@

Microsoft Visual Studio Solution File, Format Version 12.00
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GameOfLife", "GameOfLife\GameOfLife.csproj", "{980E6F7A-195D-4F06-9398-B07DD274D20A}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GameOfLife", "GameOfLife\GameOfLife.fsproj", "{980E6F7A-195D-4F06-9398-B07DD274D20A}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Expand Down
3 changes: 3 additions & 0 deletions GameOfLife/GameOfLife.csproj → GameOfLife/GameOfLife.fsproj
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,8 @@
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<Compile Include="Program.fs" />
</ItemGroup>

</Project>
125 changes: 0 additions & 125 deletions GameOfLife/Program.cs

This file was deleted.

59 changes: 59 additions & 0 deletions GameOfLife/Program.fs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
module GameOfLife.Program
open System
open System.Threading

let rows = 15
let columns = 15
let timer = 500

type Status = ``💀`` = 0 | ``😁`` = 1
type RNG = Security.Cryptography.RandomNumberGenerator
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Want a single type, but not bulky name? Use a type alias!


let private nextGeneration (grid: Status [,]) =
grid
|> Array2D.mapi (fun r c ->
let aliveNeighbors =
(seq { -1 .. 1 }, seq { -1 .. 1 })
||> Seq.allPairs
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

||> will pipe tuple items into two arguments

|> Seq.choose (function | (0, 0) -> None | x -> Some x) //skip center
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

function | is a special lambda of match cases.

|> Seq.map (fun (x, y) -> x + r, y + c)
|> Seq.filter (fun (x, y) -> x < rows && y < columns && x >= 0 && y >= 0)
|> Seq.sumBy (fun (x, y) -> int grid.[x, y])
function
// Cell is lonely and dies OR Cell dies due to over population
| Status.``😁`` when aliveNeighbors < 2 || aliveNeighbors > 3 -> Status.``💀``
// A new cell is born
| Status.``💀`` when aliveNeighbors = 3 -> Status.``😁``
// stays the same
| unchanged -> unchanged)

let private stringify (grid: Status [,]) =
grid
|> Array2D.mapi (fun _ y -> if y = columns - 1 then sprintf "%A\n" else string)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Curried form functions means multiple arguments can be invoke like nested single argument functions and vice versa. Many might not be a fan of this, but I like, the if expression returns a choice of functions from inside a two argument function to make a three argument function!

|> Seq.cast<string>
|> String.concat String.Empty

[<EntryPoint>]
let main _ =
let cts = new CancellationTokenSource()
Console.CancelKeyPress.Add(fun _ -> cts.Cancel(); Console.WriteLine "\n👋 Ending simulation.")
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

F# doesn't need semicolons, but you can swap with a new line for most things.

//Define our async work - cold
let work = async {
// randomly initialize our grid
let mutable grid =
Array2D.init rows columns (fun _ _ -> RNG.GetInt32(0, 2) |> enum)
while true do
// Displaying the grid
Console.SetCursorPosition(0, 0)
grid |> stringify |> Console.Write
grid <- nextGeneration grid
do! Async.Sleep timer
}
Comment on lines +41 to +51
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

async, unlike task, doesn't start where you declare it (cold rather than hot). Makes it easier to structure and compose.

// let's give our console
// a good scrubbing
Console.Clear()
Console.BackgroundColor <- ConsoleColor.Black
Console.CursorVisible <- false
//Do The thing
Async.RunSynchronously(work, cancellationToken = cts.Token)
0