# Intro

recently, I have been documenting my learning experience from learning F#. In the last article I wrote, I illustrated the domain logic that was flushed-out via TDD. Specifically, I implemented the logic required to identify neighboring cells. Hence, The Game of Life requires cells to change state based on the state of there neighbors.

I then refactored the logic which resulted in less code from the initial logic that my TDD had generated.

## Refactoring with Pattern Matching

**My last refactoring resulted in the following code:**

let isAbsNeighbor v1 v2 = abs (v1 - v2) = abs 1 || abs (v1 - v2) = abs 0 let IsValueNeighbor v1 v2 = if v1 >= 0 && v2 >= 0 then isAbsNeighbor v1 v2 else isAbsNeighbor v2 v1 let isNeighbor cell1 cell2 = if cell1.X <> cell2.X || cell1.Y <> cell2.Y then let xAligned = IsValueNeighbor cell1.X cell2.X let yAligned = IsValueNeighbor cell1.Y cell2.Y xAligned && yAligned else false

To be truly functional though, I decided to replace ‘if’ statements with pattern matching.

**Thus, I refactored the logic again to the following:**

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

When I was refactoring, I had got tripped up on pattern matching syntax as I documented in StackOverflow.

The most recent refactoring didn’t result in less code this time. However, the intent for this refactoring was for me to develop an understanding of Pattern Matching. For this particular example, pattern matching is probably overkill.

I then ran my unit tests and observed passing tests.

# Conclusion

In conclusion, I illustrated how I refactored the domain logic that was flushed-out via TDD. Specifically, I replaced ‘if’ statements with pattern matching.