Archive

Monthly Archives: April 2016

Intro

In my last post, I discussed my attempt at making illegal states unrepresentable. In this post I will discuss the opportunities I had to refactor that code. Thus, I will show a cleaner implementation.

Refactoring

For implementing field shots, I had wrote the following functions:

let makeTwoPointer (shooter, defender) =
    FoulShooter { Score= fieldShot (shooter, TwoPointer) }, defender

let makeThreePointer (shooter, defender) =
    FoulShooter { Score= fieldShot (shooter, ThreePointer) }, defender

For implementing foul shots, I had wrote the following functions:

let makeFoulShot  (shooter, defender) =
    FieldShooter { Score= foulShot (shooter, FoulShot) }, defender

let makeTwoFoulShots  (shooter, defender) =
    FieldShooter { Score= foulShot (shooter, TwoFoulShots) }, defender

let makeThreeFoulShots  (shooter, defender) =
    FieldShooter { Score= foulShot (shooter, ThreeFoulShots) }, defender

Thus, my client’s implementation was the following:

let results = (player1, player2) |> makeTwoPointer
                                 |> makeFoulShot
                                 |> turnover

                                 |> makeTwoPointer
                                 |> makeTwoFoulShots
                                 |> turnover

The code-smell with the functions that I wrote is that they’re duplicated with a difference in one argument when returning the result of the function. Thus, I decided to refactor this model to reduce the amount of code so that I can have better maintainability.

As a result, I refactored making foul shots from:

let makeFoulShot  (shooter, defender) =
    FieldShooter { Score= foulShot (shooter, FoulShot) }, defender

let makeTwoFoulShots  (shooter, defender) =
    FieldShooter { Score= foulShot (shooter, TwoFoulShots) }, defender

let makeThreeFoulShots  (shooter, defender) =
    FieldShooter { Score= foulShot (shooter, ThreeFoulShots) }, defender

To:

let makeFoulShots foulShots (shooter, defender) =
    FieldShooter { Score= foulShot (shooter, foulShots) }, defender

Then, I refactored making field shots from:

let makeTwoPointer (shooter, defender) =
    FoulShooter { Score= fieldShot (shooter, TwoPointer) }, defender

let makeThreePointer (shooter, defender) =
    FoulShooter { Score= fieldShot (shooter, ThreePointer) }, defender

To:

let makeFieldBasket fieldBasket (shooter, defender) =
    FoulShooter { Score= fieldShot (shooter, fieldBasket) }, defender

Thus, my client was then updated from:

let results = (player1, player2) |> makeTwoPointer
                                 |> makeFoulShot
                                 |> turnover

                                 |> makeTwoPointer
                                 |> makeTwoFoulShots
                                 |> turnover

To:

let results = (player1, player2) |> makeFieldBasket TwoPointer
                                 |> makeFoulShots   FoulShot
                                 |> turnover

                                 |> makeFieldBasket TwoPointer
                                 |> makeFoulShots   TwoFoulShots
                                 |> turnover

The old domain model was this:

(*Types*)
type Player = { Score:int }

type FieldShot = TwoPointer| ThreePointer
type FoulShots = FoulShot  | TwoFoulShots | ThreeFoulShots

type FoulShooter  = FoulShooter  of Player
type FieldShooter = FieldShooter of Player

(*Functions*)
let shoot lastShot player =
    (player.Score + lastShot)

let turnover (shooter, defender) =
    (defender, shooter)

// ** Field shots **
let fieldShot (fieldShooter, shot) =

    let player = match fieldShooter with
                 | FieldShooter player -> player

    match player.Score with
    | score when score >= 33 -> score
    | _ ->  match (fieldShooter, shot) with
            | FieldShooter player, shot -> match shot with
                                           | TwoPointer   -> player |> shoot 2
                                           | ThreePointer -> player |> shoot 3
let makeTwoPointer (shooter, defender) =
    FoulShooter { Score= fieldShot (shooter, TwoPointer) }, defender

let makeThreePointer (shooter, defender) =
    FoulShooter { Score= fieldShot (shooter, ThreePointer) }, defender

// ** Foul shots **
let foulShot (foulShooter, shot) =

    let player = match foulShooter with
                 | FoulShooter player -> player

    match player.Score with
    | score when score >= 33 -> score
    | _ ->  match (foulShooter, shot) with
            | FoulShooter player, shot -> match shot with
                                          | FoulShot       -> player |> shoot 1
                                          | TwoFoulShots   -> player |> shoot 2
                                          | ThreeFoulShots -> player |> shoot 3
let makeFoulShot  (shooter, defender) =
    FieldShooter { Score= foulShot (shooter, FoulShot) }, defender

let makeTwoFoulShots  (shooter, defender) =
    FieldShooter { Score= foulShot (shooter, TwoFoulShots) }, defender

let makeThreeFoulShots  (shooter, defender) =
    FieldShooter { Score= foulShot (shooter, ThreeFoulShots) }, defender

The refactored domain model is the following:

(*Types*)
type Player = { Score:int }

type FieldShot = TwoPointer| ThreePointer
type FoulShots = FoulShot  | TwoFoulShots | ThreeFoulShots

type FoulShooter  = FoulShooter  of Player
type FieldShooter = FieldShooter of Player

(*Functions*)
let shoot lastShot player =
    (player.Score + lastShot)

let fieldShot (fieldShooter, shot) =

    let player = match fieldShooter with
                 | FieldShooter player -> player

    match player.Score with
    | score when score >= 33 -> score
    | _ ->  match (fieldShooter, shot) with
            | FieldShooter player, shot -> match shot with
                                           | TwoPointer   -> player |> shoot 2
                                           | ThreePointer -> player |> shoot 3

let makeFieldBasket fieldBasket (shooter, defender) =
    FoulShooter { Score= fieldShot (shooter, fieldBasket) }, defender

let foulShot (foulShooter, shot) =

    let player = match foulShooter with
                 | FoulShooter player -> player

    match player.Score with
    | score when score >= 33 -> score
    | _ ->  match (foulShooter, shot) with
            | FoulShooter player, shot -> match shot with
                                          | FoulShot       -> player |> shoot 1
                                          | TwoFoulShots   -> player |> shoot 2
                                          | ThreeFoulShots -> player |> shoot 3

let makeFoulShots foulShots (shooter, defender) =
    FieldShooter { Score= foulShot (shooter, foulShots) }, defender

let turnover (shooter, defender) =
    (defender, shooter)

Conclusion

In conclusion, In my last post, I discussed my attempt at making illegal states unrepresentable. In this post I discussed the opportunities I had to refactor that code. I then refactored it.

Intro

I have been going HAM on F# during my off hours. In doing so, I have been writing and rewriting F# code to practice Domain Driven Design such that illegal states of a program cannot be compiled.

The Game of Thirty-Three

The basketball game Thirty-Three has the following rules:
1. Players must shoot either a Two-pointer, Three-pointer, or foul shots.
2. A player can only shoot foul shots after they scored a Two-pointer or Three-pointer (aka: field shot).
3. A player can shoot up to three foul shots after making a field shot.
4. If a player makes all three foul shots, then the player’s next shot must be a field shot.
5. If a player does not make all three foul shots then the player can shoot another field shot or turnover the ball.
6. The game is over when a player scores thirty-three or more points.

I implemented this game as a kata. In doing so, I wanted to enforce these rules such that a violation of these rules cannot be compiled.

The following code reflects a legal state:

(*Client*)
let player1, player2 = FieldShooter { Score=0 } ,
                       FieldShooter { Score=0 }

let results = (player1, player2) |> makeTwoPointer
                                 |> makeFoulShot

The output is as follows:
val player2 : FieldShooter = FieldShooter {Score = 0;}
val player1 : FieldShooter = FieldShooter {Score = 0;}
val results : FieldShooter * FieldShooter =
(FieldShooter {Score = 3}, FieldShooter {Score = 0})

The following code reflects a illegal state:

(*Client*)
let player1, player2 = FieldShooter { Score=0 } ,
                       FieldShooter { Score=0 }

let results = (player1, player2) |> makeTwoPointer
                                 |> makeTwoPointer

The output is as follows:
error FS0001: Type mismatch. Expecting a
FoulShooter * FieldShooter -> ‘a
but given a
FieldShooter * ‘b -> FoulShooter * ‘b
The type ‘FoulShooter’ does not match the type ‘FieldShooter’

Again, when a player scores a field shot (i.e. Two-pointer or Three-pointer), then they must shoot foul shots. The above code attempts to shoot two two-pointers in a row. Thus, this would result in an illegal state. Thus, the code cannot be compiled.

The domain model is the following:

(*Types*)
type Player = { Score:int }

type FieldShot = TwoPointer| ThreePointer
type FoulShots = FoulShot  | TwoFoulShots | ThreeFoulShots

type FoulShooter  = FoulShooter  of Player
type FieldShooter = FieldShooter of Player

(*Functions*)
let shoot lastShot player =
    (player.Score + lastShot)

let turnover (shooter, defender) =
    (defender, shooter)

// ** Field shots **
let fieldShot (fieldShooter, shot) =

    let player = match fieldShooter with
                 | FieldShooter player -> player

    match player.Score with
    | score when score >= 33 -> score
    | _ ->  match (fieldShooter, shot) with
            | FieldShooter player, shot -> match shot with
                                           | TwoPointer   -> player |> shoot 2
                                           | ThreePointer -> player |> shoot 3
let makeTwoPointer (shooter, defender) = 
    FoulShooter { Score= fieldShot (shooter, TwoPointer) }, defender

let makeThreePointer (shooter, defender) = 
    FoulShooter { Score= fieldShot (shooter, ThreePointer) }, defender

// ** Foul shots **
let foulShot (foulShooter, shot) =

    let player = match foulShooter with
                 | FoulShooter player -> player

    match player.Score with
    | score when score >= 33 -> score
    | _ ->  match (foulShooter, shot) with
            | FoulShooter player, shot -> match shot with
                                          | FoulShot       -> player |> shoot 1
                                          | TwoFoulShots   -> player |> shoot 2
                                          | ThreeFoulShots -> player |> shoot 3
let makeFoulShot  (shooter, defender) = 
    FieldShooter { Score= foulShot (shooter, FoulShot) }, defender

let makeTwoFoulShots  (shooter, defender) = 
    FieldShooter { Score= foulShot (shooter, TwoFoulShots) }, defender

let makeThreeFoulShots  (shooter, defender) = 
    FieldShooter { Score= foulShot (shooter, ThreeFoulShots) }, defender

(*Client*)
let player1, player2 = FieldShooter { Score=0 } ,
                       FieldShooter { Score=0 }

let results = (player1, player2) |> makeTwoPointer
                                 |> makeFoulShot
                                 |> turnover

                                 |> makeTwoPointer
                                 |> makeTwoFoulShots
                                 |> turnover

                                 |> makeThreePointer
                                 |> makeTwoFoulShots
                                 |> turnover

                                 |> makeThreePointer
                                 |> makeThreeFoulShots
                                 |> makeThreePointer
                                 |> makeThreeFoulShots
                                 |> makeThreePointer
                                 |> makeThreeFoulShots
                                 |> makeThreePointer
                                 |> makeThreeFoulShots
                                 |> makeThreePointer
                                 |> makeThreeFoulShots
                                 |> makeThreePointer
                                 |> turnover
                                 |> makeThreePointer

Conclusion

In conclusion, I have been going HAM on F# during my off hours. In doing so, I have been writing and rewriting F# code to practice Domain Driven Design such that illegal states of a program cannot be compiled.

Intro

In my last article, I discussed my attempt of practicing Domain Driven Design via F#. As proud as I was of my progress in learning F# in combination with Domain Driven Design, there were some refactoring opportunities that I wanted to take.

Decoupling Data from Behavior

In the last article, I had created two literals. One literal was for the target number of points that players would play up to. The other literal was the maximum number of allowed foul shots.

The literals were implemented as follows:

[<Literal>]
let Objective = 33

[<Literal>]
let MaxFoulShots = 3

I used these literals in the active pattern function:

let (|Underway|AlmostGame|Game|) (score,shot) =
 
    let shotValue = match shot with
                    | FoulShot                      -> 1
                    | TwoPointer   | TwoFoulShots   -> 2
                    | ThreePointer | ThreeFoulShots -> 3
 
    match score, shotValue with
    | Underway   s,v -> if (s + v) <= (Objective - MaxFoulShots)
                        then Underway   (s + v)
                        else AlmostGame (s + v)
 
    | AlmostGame s,v -> if ( (s+v) < Objective )
                        then AlmostGame (s + v)
                        else Game Objective
 
    | GameTime   s,v -> Game s

Specifically, in this block here:

    match score, shotValue with
    | Underway   s,v -> if (s + v) <= (Objective - MaxFoulShots)
                        then Underway   (s + v)
                        else AlmostGame (s + v)
 
    | AlmostGame s,v -> if ( (s+v) < Objective )
                        then AlmostGame (s + v)
                        else Game Objective
 
    | GameTime   s,v -> Game s

What I don’t like about the above function, is that I feel like the function depends on an external power in order to deliver a result. Hence, my function relies on the hardcoded data “33” and “3” for the total number of points (i.e. “Objective”) and the maximum foul shots allowed (i.e. 3) respectively. Again, I feel as if this data was just planted into my function inorganically.

To remedy this code smell, I decided to practice the art of decoupling data from behavior. Thus, I replaced the literals in my code with a record type called Rules. Thus, this record type would be leveraged as a parameter for my active pattern function. Hence, my active pattern function determines the stage of a game based on a shooter’s score.

The following record type was created:

Rules = {
 Target:int
 MaxFoulShots:int
}

The active pattern was modified to the following:

let (|Underway|AlmostGame|Game|) (score, shot, rules) =

    let shotValue = match shot with
                    | FoulShot                      -> 1
                    | TwoPointer   | TwoFoulShots   -> 2
                    | ThreePointer | ThreeFoulShots -> 3

    match score, shotValue with
    | Underway   s,v -> if (s + v) <= (rules.Target - rules.MaxFoulShots)
                        then Underway   (s + v)
                        else AlmostGame (s + v)

    | AlmostGame s,v -> if ( (s+v) < rules.Target )
                        then AlmostGame (s + v)
                        else Game rules.Target

    | Game       s,v -> Game s

Pattern matching can leverage Active Patterns for enhanced readability. Thus, my function, makeShot, was updated to call the active pattern.

The makeShot function was the following:

let makeShot shot (shooter, defender) =

    match (shooter.Score, shot) with
    | Underway p   -> { shooter with Score=Underway p },   defender
    | AlmostGame p -> { shooter with Score=AlmostGame p }, defender
    | Game p       -> { shooter with Score=GameTime p },   defender

To incorporate the rules, I refactored makeShot to the following:

let makeShot shot (players, rules) =

    let shooter = players.Shooter
    let defender = players.Defender
    let game = shooter.Score, shot, rules

    match game with
    | Underway p   ->  { Shooter = { shooter with Score=Underway p }
                         Defender =  defender },
                         rules

    | AlmostGame p ->  { Shooter = { shooter with Score=AlmostGame p }
                         Defender =  defender },
                         rules

    | Game p       ->  { Shooter = { shooter with Score=Game p }
                         Defender =  defender },
                         rules

If you’ve noticed in the above code, I replaced the shooter and defender tuple with a record type called players. This decision was made because I found myself using this tuple of players in a number of places without any metadata about the order of the players within the tuple. That’s when I decided to create a type to define player roles.

The Players record type is the following:

type Players = {
      Shooter:PlayerScore
      Defender:PlayerScore
}

I then wrote a function to establish a change of role for the players:

let changePossession players = { Shooter=  players.Defender
                                 Defender= players.Shooter }

Refactoring the Client

Based on the alterations that I’ve made to the domain model, I had to refactor the client code in order for my program to compile.

The client for the game is the following:

// ************************************************************
(*Client*)
// ************************************************************
let players = startGame
let rules = { Target=33; MaxFoulShots=3 }

let firstPossession, _ = (players, rules) |> makeShot TwoPointer
let turnOver = firstPossession |> changePossession, rules

let final = turnOver |> makeShot ThreePointer
                     |> makeShot FoulShot

                     |> makeShot ThreePointer
                     |> makeShot TwoFoulShots

                     |> makeShot ThreePointer
                     |> makeShot ThreeFoulShots

                     |> makeShot ThreePointer
                     |> makeShot ThreePointer
                     |> makeShot ThreePointer
                     |> makeShot ThreePointer
                     |> makeShot ThreePointer

                     |> makeShot FoulShot
                     |> makeShot FoulShot
                     |> makeShot ThreeFoulShots

The entire domain model is this:

module Game
// ************************************************************
(*Types*)
// ************************************************************
type Player = | Player1 | Player2

type Players = {
      Shooter:PlayerScore
      Defender:PlayerScore
}

and PlayerScore = {
      Player:Player
      Score:Game
}

and Rules = {
     Target:int
     MaxFoulShots:int
}

and Shot =
    | TwoPointer| ThreePointer
    | FoulShot  | TwoFoulShots | ThreeFoulShots

and Game =
    | Underway of int
    | AlmostGame of int
    | Game of int

// ************************************************************
(*Functions*)
// ************************************************************
let (|Underway|AlmostGame|Game|) (score, shot, rules) =

    let shotValue = match shot with
                    | FoulShot                      -> 1
                    | TwoPointer   | TwoFoulShots   -> 2
                    | ThreePointer | ThreeFoulShots -> 3

    match score, shotValue with
    | Underway   s,v -> if (s + v) <= (rules.Target - rules.MaxFoulShots)
                        then Underway   (s + v)
                        else AlmostGame (s + v)

    | AlmostGame s,v -> if ( (s+v) < rules.Target )
                        then AlmostGame (s + v)
                        else Game rules.Target

    | Game       s,v -> Game s

let makeShot shot (players, rules) =

    let shooter = players.Shooter
    let defender = players.Defender
    let game = shooter.Score, shot, rules

    match game with
    | Underway p   ->  { Shooter = { shooter with Score=Underway p }
                         Defender =  defender },
                         rules

    | AlmostGame p ->  { Shooter = { shooter with Score=AlmostGame p }
                         Defender =  defender },
                         rules

    | Game p       ->  { Shooter = { shooter with Score=Game p }
                         Defender =  defender },
                         rules

let startGame = { Shooter=  { Player=Player1; Score=Underway 0 }
                  Defender= { Player=Player2; Score=Underway 0 } }

let changePossession players = { Shooter=  players.Defender
                                 Defender= players.Shooter }

// ************************************************************
(*Client*)
// ************************************************************
let players = startGame
let rules = { Target=33; MaxFoulShots=3 }

let firstPossession, _ = (players, rules) |> makeShot TwoPointer
let turnOver = firstPossession |> changePossession, rules

let final = turnOver |> makeShot ThreePointer
                     |> makeShot FoulShot

                     |> makeShot ThreePointer
                     |> makeShot TwoFoulShots

                     |> makeShot ThreePointer
                     |> makeShot ThreeFoulShots

                     |> makeShot ThreePointer
                     |> makeShot ThreePointer
                     |> makeShot ThreePointer
                     |> makeShot ThreePointer
                     |> makeShot ThreePointer

                     |> makeShot FoulShot
                     |> makeShot FoulShot
                     |> makeShot ThreeFoulShots

Intro

I must admit. I’m not an expert at Domain-Driven Design. However, I do find it interesting that most people actually design their domain upfront instead of test driving their design. Honestly, I prefer TDD over DDD. Hence, I feel that TDD encourages me to write the bare minimum to flush out my domain logic. Thus, I will argue that the less code exposed to solve a problem, the less room for bugs to surface.

The Game of Thirty-Three

I recently decided to build the domain model for the basketball game “Thirty-three”. On the mean streets of Cleveland, we play Thirty-Three. However, in softer cities such as Charlotte, it is common for people to play Twenty-One.

Regardless of how hardened the culture is of a city, I decided to practice DDD by writing the popular basketball game of “Thirty-Three”.

The following reflects the actors in the game:

type Player = | Player1 | Player2

The following reflects the state of a game:

Game = 
    | Underway of int
    | AlmostGame of int
    | GameTime of int

A game has three major stages:

1. It starts (i.e. underway).
2. It nears completion (i.e. AlmostGame)
3. It ends (i.e. GameTime).

The reason why I wrote the case, AlmostGameTime, is because a player only needs to score 33 points when a he/she shoots from the foul line in order to win. Hence, there is no reason for a player to score 32 points and then shoot two or more foul shots. All the player needs is just one foul shot regardless of the foul shots awarded. Thus, I implemented some logic to account for this specific rule.

The type below serves as a container for a player’s state within the game:

type PlayerScore = {Player:Player; Score:Game}

The following reflects how a player can score:

type Shot = 
     | TwoPointer| ThreePointer
     | FoulShot  | TwoFoulShots | ThreeFoulShots

In the code above, I identified the various methods in which points can be scored by a player. Specifically, a player can score a two-pointer, a three-pointer, or foul shots. In addition, a payer can shoot one to three foul shots.

Defining Literals

I decided to declare the following literals for my basketball game:

[<Literal>]
let Objective = 33

[<Literal>]
let MaxFoulShots = 3

The above literals serves as the game’s parameters. In the functions that I implemented, I rely on these literals to enforce the rules of the game.

Functions

After defining types and literals, I then had to implement the functions for the game.

The following functions were implemented:

let (|Underway|AlmostGame|Game|) (score,shot) =

    let shotValue = match shot with
                    | FoulShot                      -> 1
                    | TwoPointer   | TwoFoulShots   -> 2
                    | ThreePointer | ThreeFoulShots -> 3

    match score, shotValue with
    | Underway   s,v -> if (s + v) <= (Objective - MaxFoulShots)
                        then Underway   (s + v)
                        else AlmostGame (s + v)

    | AlmostGame s,v -> if ( (s+v) < Objective )
                        then AlmostGame (s + v)
                        else Game Objective

    | GameTime   s,v -> Game s

let makeShot shot (shooter, defender) =

    match (shooter.Game, shot) with
    | Underway p   -> { shooter with Game=Underway p },   defender
    | AlmostGame p -> { shooter with Game=AlmostGame p }, defender
    | Game p       -> { shooter with Game=GameTime p },   defender

let startGame = 

    let player1Score = { Player=Player1; Game=Underway 0 }
    let player2Score = { Player=Player2; Game=Underway 0 }

    (player1Score, player2Score)

Examining functions:

The following function is an active pattern:

let (|Underway|AlmostGame|Game|) (score,shot) =

    let shotValue = match shot with
                    | FoulShot                      -> 1
                    | TwoPointer   | TwoFoulShots   -> 2
                    | ThreePointer | ThreeFoulShots -> 3

    match score, shotValue with
    | Underway   s,v -> if (s + v) <= (Objective - MaxFoulShots)
                        then Underway   (s + v)
                        else AlmostGame (s + v)

    | AlmostGame s,v -> if ( (s+v) < Objective )
                        then AlmostGame (s + v)
                        else Game Objective

    | GameTime   s,v -> Game s

This active pattern yields a specific stage of the game to the client. The function takes the player’s score and his/her most recent shot. Thus, the values of those parameters are used to identify the player’s state within the game and that state will be returned to the client caller as a math to their pattern matching construct.

Starting the Game

I wrote the following function to initiate the game:

let startGame = 

    let player1Score = { Player=Player1; Score=Underway 0 }
    let player2Score = { Player=Player2; Score=Underway 0 }

    (player1Score, player2Score)

In the above code, I set each player’s points to zero and set the stage of the game to underway.

The following function serves as the core function to the model:

let makeShot shot (shooter, defender) =

    match (shooter.Score, shot) with
    | Underway p   -> { shooter with Score=Underway p },   defender
    | AlmostGame p -> { shooter with Score=AlmostGame p }, defender
    | Game p       -> { shooter with Score=GameTime p },   defender

The above function leverages the active pattern that I discussed earlier. This function takes the most recent shot as well as a tuple reflecting the scores of the shooter and defender. Ultimately, this function generates the latest state of the game based on the shot made by the shooter.

The entire domain model is as follows:

module Game
// ************************************************************
(*Types*)
// ************************************************************
type Player = | Player1 | Player2

type PlayerScore = {Player:Player; Score:Game}

and Shot = 
     | TwoPointer| ThreePointer
     | FoulShot  | TwoFoulShots | ThreeFoulShots

and Game = 
    | Underway of int
    | AlmostGame of int
    | GameTime of int

[<Literal>]
let Objective = 33

[<Literal>]
let MaxFoulShots = 3

// ************************************************************
(*Functions*)
// ************************************************************
let (|Underway|AlmostGame|Game|) (score,shot) =

    let shotValue = match shot with
                    | FoulShot                      -> 1
                    | TwoPointer   | TwoFoulShots   -> 2
                    | ThreePointer | ThreeFoulShots -> 3

    match score, shotValue with
    | Underway   s,v -> if (s + v) <= (Objective - MaxFoulShots)
                        then Underway   (s + v)
                        else AlmostGame (s + v)

    | AlmostGame s,v -> if ( (s+v) < Objective )
                        then AlmostGame (s + v)
                        else Game Objective

    | GameTime   s,v -> Game s

let makeShot shot (shooter, defender) =

    match (shooter.Score, shot) with
    | Underway p   -> { shooter with Score=Underway p },   defender
    | AlmostGame p -> { shooter with Score=AlmostGame p }, defender
    | Game p       -> { shooter with Score=GameTime p },   defender

let startGame = 

    let player1Score = { Player=Player1; Score=Underway 0 }
    let player2Score = { Player=Player2; Score=Underway 0 }

    (player1Score, player2Score)

The Client

I wrote the following client to consume the domain model:

// ************************************************************
(*Client*)
// ************************************************************
let player1Score, player2Score = startGame

let player1, player2 = (player1Score, player2Score) |> makeShot TwoPointer
let shooter, defender = player2, player1

let final = (shooter, defender) |> makeShot ThreePointer
                                |> makeShot FoulShot

                                |> makeShot ThreePointer
                                |> makeShot TwoFoulShots

                                |> makeShot ThreePointer
                                |> makeShot ThreeFoulShots

                                |> makeShot ThreePointer
                                |> makeShot ThreePointer
                                |> makeShot ThreePointer
                                |> makeShot ThreePointer
                                |> makeShot ThreePointer

                                |> makeShot FoulShot
                                |> makeShot FoulShot
                                |> makeShot ThreeFoulShots

Conclusion

In conclusion, I provided an example of how to implement a domain model for the Game of Thirty-Three.

Intro

Since my contract has ended, I have been using my unemployment to dig deeper into F#. Finally, it’s beginning to click for me. Now as I reason with my code, I recognize opportunities for some open source utilities.

As a result of my observation, I decided to contribute an active pattern library to NuGet. It’s Bizmonger.ActivePatterns.

module ValuesAP

let (|Equal|Different|) = function
    | v1, v2 when v1 = v2 -> Equal
    | _                   -> Different

module ListsAP

let (|None|One|Many|) (x:'a list) =
    match x with
    | x when x.Length > 1 -> Many
    | x when x.Length = 1 -> One
    | _                   -> None

module NumbersAP

let (|Positive|Neutral|Negative|) = function
    | x when x > 0 -> Positive
    | x when x < 0 -> Negative
    | _            -> Neutral

Here’s a sample of how to use the NumbersAP active pattern

let result = match -5 with
             | Positive -> "is positive"
             | Negative -> "is negative"
             | Neutral  -> "is neutral"

I think adding “AP” as a suffix to module names may be the way to go. Hence, this convention is used with JavaScript libraries. Thus, I plan on adding more active patterns to this package as I continue to build solutions.

Conclusion

In conclusion, since my contract has ended, I have been using my unemployment to dig deeper into F#. Finally, it’s beginning to click for me. Now as I reason with my code, I recognize opportunities for some open source utilities.

As a result of my observation, I decided to contribute an active pattern library to NuGet. It’s Bizmonger.ActivePatterns.

Intro

I recently learned how to pattern match on object types. This may be necessary at times or could be an issue with one’s design. In either case, I will attempt to articulate how to pattern match on the container type of union cases within a discriminated union.

The Pattern Construct “:?”

In this example, I created a vehicle type with some union cases and created a function called isVehicle.

type Vehicle = 
    | Car
    | Tank
    | Helicopter

let isVehicle = fun (a:obj) ->; match a with
                               | 😕 Vehicle ->; &amp;quot;Is a vehicle&amp;quot; // on word press &amp;quot;:?&amp;quot; shows as a smiley face
                               | _         ->; &amp;quot;Is NOT a vehicle&amp;quot;

Car |>; isVehicle

The isVehicle function requires the value argument to be annotated with type object in order for pattern matching on types to work correctly. We then use the pattern construct “:?” to match on types.

Conclusion

In conclusion, I recently learned how to pattern match on object types. This may be necessary at times or could be an issue with one’s design. In either case, I attempted to articulate how to pattern match on the container type of union cases within a discriminated union.

Intro

I recently returned to my Game of Life implementation after taking two weeks off. Upon returning, I observed certain pieces of code that jumped out at me. Specifically, I observed some minor duplication of function calls.

let updateCells (grid:Map<(int * int), Cell>) =
 
    grid |> Map.toSeq
         |> Seq.map snd
         |> Seq.fold (fun grid c -> grid |> setReaction (c.X, c.Y)) grid

let mutable _cells = ObservableCollection<Cell>( grid |> Map.toSeq
                                                      |> Seq.map snd
                                                      |> Seq.toList )
let cycleHandler _ = 
 
    self.Cells <- ObservableCollection<Cell>( grid |> cycleThroughCells
                                                   |> Map.toSeq
                                                   |> Seq.map snd
                                                   |> Seq.toList )

If you’ve noticed, the following code appears in all three functions:

grid |> Map.toSeq
     |> Seq.map snd

This is only two lines of code. However, I often challenge myself to reduce the footprint that I leave for my clients. I guess my thought process is analogous to a surgeon that wants to leave the smallest scar possible when performing surgery.

So how can we resolve this duplication of code?

Function Composition

Within functional programming, we can fuse functions together so that they can become one function.

To do this, let’s create a new function from the duplicated sequence of functions:

let getCells = Map.toSeq >> Seq.map snd >> Seq.toList

Now if you’re attentive, you will have noticed that we don’t use any arguments when using Function Composition. Hence, the grid value is not used. The reason behind this is because of Partial Application.

Partial Application

I’m still learning all these functional programming techniques. However, my understanding is that partial application is a technique within functional programming that postpones the need to accept a complete set of arguments for a given function. In other words, partial application is the act of deferring the acceptance of a complete set of arguments for a given function in which there is an expectation that the end-client will provide the rest of the arguments later. At least, that’s my understanding.

We can now take a function like:

let updateCells (grid:Map<(int * int), Cell>) =
 
    grid |> Map.toSeq
         |> Seq.map snd
         |> Seq.fold (fun grid c -> grid |> setReaction (c.X, c.Y)) grid

And refactor it to something like:

let updateCells (grid:Map<(int * int), Cell>) =
 
    grid |> getCells
         |> Seq.fold (fun grid c -> grid |> setReaction (c.X, c.Y)) grid

Conclusion

In conclusion, I recently returned to my Game of Life implementation after taking two weeks off. Upon returning, I observed certain pieces of code that jumped out at me. Specifically, I observed some minor duplication of function calls. I then implemented Function Composition and Partial Application to reduce duplication.