Learning F#: The Game of Life (Vol. 8)

Intro

In the last article, I raised an impediment on how I was unable to launch the WPF application window. That issue has been resolved. In addition, I learned why I should be using the fold function.

Launching a WPF App

As I detailed in the last article, I struggled to actually launch the WPF app. I was able to resolve this by adding a couple of Nuget packages to my client executable.

I added:
* FSharp.ViewModel.Core
* FsXAML.Wpf

I then added a App.fs file:

module MainApp

open System
type App = FsXaml.XAML<"App.xaml">
[<STAThread;EntryPoint>]
let main _ = App().Root.Run()

The App.fs file needs to be the last file in the project in order for this to work. After, I made the above alterations, things just worked.

Leveraging the Fold Function

To update all of the cells of the grid I attempted to use the following code:

let cycleThroughCells (grid:Map<(int * int), Cell>) =

    grid |> Map.toSeq
         |> Seq.map snd
         |> Seq.map (fun c -> grid |> setReaction (c.X, c.Y)) 
         |> Seq.last

I think the above code would work for capturing the latest state of the grid in regards to active cells. However, there existed a functional friendly way of doing this as well. Whenever there is a collection to be processed that results in some state being updated, then one should strongly consider using the fold method.

The following code accomplishes the same thing:

let cycleThroughCells (grid:Map<(int * int), Cell>) =

    grid |> Map.toSeq
         |> Seq.map snd
         |> Seq.fold (fun grid c -> grid |> setReaction (c.X, c.Y)) grid

What I learned from the code above is that a fold is essentially an iter function that applies each element operation to the state passed in and returns the state.

Conclusion

In the last article, I raised an impediment on how I was unable to launch the WPF application window. That issue has been resolved. In addition, I learned why I should be using the fold function.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: