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

Intro

As I have detailed in past articles, I have made a declaration to learn F#. Thus, I have decided to implement the Game of Life to support my journey. In several of my posts, I have refined the logic generated by TDD. Thus, I continue to find new ways to frame my logic.

Switches in F# aren’t just for constants

Coming from a C# background, I have always thought that switches can only operate on constants. However, with pattern matching in F#, we have more flexibility. Thus, we can pattern match on expressions. In addition, I think F# has its own form of encapsulating private helpers. Hence, we can embed helper functions within public functions so that the helper functions are not exposed to the world.

So once again, I decided to refactor yet again.
From:

let isAbsNeighbor v1 v2 =
    abs (v1 - v2) = abs 1 ||
    abs (v1 - v2) = abs 0

let IsValueNeighbor v1 v2 =
    match v1, v2 with
    | v1, v2 when v1 >= 0
              &&  v2 >= 0 -> isAbsNeighbor v1 v2
    | _                   -> isAbsNeighbor v2 v1

let isNeighbor cell1 cell2 =
    match cell1, cell2 with
    | cell1, cell2 when cell1.X <> cell2.X
                    ||  cell1.Y <> cell2.Y -> let xAligned = IsValueNeighbor cell1.X cell2.X
                                              let yAligned = IsValueNeighbor cell1.Y cell2.Y

                                              xAligned && yAligned
    | _ -> false

To:

let isNeighbor cell1 cell2 =

    let isAbsNeighbor v1 v2 =
        match abs (v1 - v2) with
        | 0 | 1 -> true
        | _     -> false

    let isValueNeighbor v1 v2 =
        match v1 >= 0
          &&  v2 >= 0 with
        | true  -> isAbsNeighbor v1 v2
        | _     -> isAbsNeighbor v2 v1

    match cell1.X <> cell2.X
      ||  cell1.Y <> cell2.Y with
    | true ->   isValueNeighbor cell1.X cell2.X
             && isValueNeighbor cell1.Y cell2.Y
    | _    -> false

In the refactored code above, I lifted the hard-coded expressions into the match condition. I then took the functions that were really helper functions and embedded them inside my main function to support  encapsulation.

Conclusion

In conclusion, I have detailed in past articles, I have made a declaration to learn F#. Thus, I have decided to implement the Game of Life to support my journey. In several of my posts, I have refined the logic generated by TDD. Thus, I continue to find new ways to frame my logic.

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: