© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2025

A. Antich Magical Haskell https://doi.org/10.1007/979-8-8688-1282-8_8

8. Blackjack: Full Haskell Program

Anton Antich 1    

(1)

Schaffhausen, Schaffhausen, Switzerland

Now we are ready to apply everything we’ve learned and design and then build the Blackjack program from scratch to win the Haskell magician competition. This is the only chapter where we will carefully discuss step by step building a program from nothing to fully functional, down to the “main” function . It should allow you to follow the logic and then apply it when building your own, much more complicated projects, as well as follow the more advanced concepts we will be reviewing in the next chapters.

Let us recall the simplified Blackjack rules that we decided to implement :

  • The dealer deals two cards to each player and one card to themselves.

  • Players make bets (we will not allow any splits and others to simplify the game).

  • Players take cards until they say “stop” or go bust (over 21 total score).

  • The dealer takes cards until they hit 17 or go bust.

  • The score is calculated as 10 for J, Q, K, either 1 or 11 for Ace, and at face value for the other cards.

  • If the player is closer to 21 than the dealer, they get paid their bet; otherwise, they lose it.

  • If the player gets 21 from the initial dealing, they win 2× their bet.

Another simplification we will make is that we will make our game single player. Now we will forget somewhat painful, but very educational, exercises that we did for the Cards domain when we “invented” the State monad for the DeckM type and will rather use all the power of existing Haskell libraries. Let us recap and apply the process to solve problems in the functional way:

  • Design the problem domain in terms of types. We did most of this work in the previous chapters. Now we’ll just need to expand it to include types that will help us handle state and input/output – and thanks to the previous chapter, we now can.

  • Think how we will structure the whole program in terms of the monad transformer stack. 1 As discussed in the last chapter, IO will always be at the bottom, and then the usual choice is Reader, Writer, and State to manage tasks related to configuration, logging, and state. In many real-world tasks, you will also need some way to handle errors – a separate topic as there are different approaches to deal with this in Haskell, but adding another monad to the stack for error handling is quite common as well. For our simplified Blackjack program, we will only use State on top of IO – adding new layers adds nothing new in terms of the concepts learned, and you’ll easily expand this approach to more complex stacks. We will also have examples of those in the next chapters.

  • Design additional types and functions that live on corresponding “floors” of our monad transformer stack. Design additional interface functions on top of the standard typeclass functions if needed (e.g., if we have several monads in the stack – providing functions that combine “lifts” of different sizes may prove handy).

  • Then everything that’s left is connecting our functions – “spells” – so that the types compose. And voila! Our program is ready!

PREPARATION EXERCISE

Review the types and functions we have designed for the Cards domain in the previous chapters. Think about what is lacking to handle the state of the game and what input/output functions you are going to need. Separate them into different monad stack “floors.”

Diagram illustrating the concept of a Game Monad, which combines State and IO. On the left, a purple box labeled "Game Monad, combining State and IO" contains two sections: "State Transformer StateT s m a" and "IO." An arrow points from a blue cloud labeled "Pure Types and Functions" on the right towards the Game Monad, indicating the flow or transformation from pure functions to the monad structure.

Figure 8-1

Thinking about program design. Pure types and functions describe our problem domain as much as possible. They are then used inside our monad stack as needed to perform computations with mathematically guaranteed results, while side effects of changing state and interacting with the user are hidden inside the respective monads and will never pollute our pure world

Let’s roll up our sleeves and get to work!

Preparation

By now you should have installed Haskell from Haskell.org – the specific ways to do that change with time, but the website should remain. Haskell uses tools called cabal and stack for package management and for developing your projects. We will not be discussing in detail their usage; they both have great extensive documentation, and I encourage you to review it. Stack is enough for most practical purposes, so I suggest you start there. Another necessary resource for Haskell development is hackage.haskell.org – it contains all libraries that you will use in your practical development. So whenever I reference libraries such as transformers or mtl , go to Hackage and search for them to read the detailed documentation.

The code that we will be discussing in this chapter is in the book’s GitHub repository in the folder for Chapter 8 .

To start the new Haskell project, go to your development folder and run stack new <project_name> , which will create the new folder and initialize some default settings. Normally, the directory structure will be similar to the one shown in Figure 8-2 . You can use your favorite coding editor for Haskell development – VS Code, Atom, or even vi or emacs if you are into terminals (but then you probably don’t need to read this book to be fair).

A file directory structure is displayed, showing folders and files for a software project. Folders include ".stack-work," "app," "src," and "test." Files listed are ".gitignore," "cards.cabal," "CHANGELOG.md," "LICENSE," "package.yaml," "README.md," "Setup.hs," and "stack.yaml." Some items are highlighted in red, indicating potential changes or importance.

Figure 8-2

Typical Haskell project structure

Usually, we put all the “libraries” code in the src folder, while app is the “default” executable folder that will contain the file with our main function code. We can have several executables in one project as we will see down the line. Go to package.yaml and review it – it contains various project settings, which are pretty self-explanatory. For now, simply change the executable name to “blackjack” as shown below and keep the rest intact:

...

library:

  source-dirs: src

executables:

   blackjack :

    main:                Main.hs

    source-dirs:         app

    ghc-options:

Now, edit the Main.hs file in the app folder and put a placeholder main function there:

main = putStrLn "Hello World"

After that, in the terminal run a couple of stack commands:

stack build

stack exec blackjack

This should build your project (may take a slightly long time the first time as stack will need to download all needed dependencies and build them as well) and then run it, which will display “Hello World”.

There is one important setting in stack.yaml file called “resolver.” You can keep it as is if you are just starting out, but it defines all the versions of all the libraries and GHC – so pick carefully in real projects. Usually some “lts” setting is the best, as it will set up dependencies for long-term supported libraries.

Now that we have a basic project structure setup, we are ready to design and code.

Initial “Pure” Design

First, we should always start with thinking about our problem domain and how it can be efficiently represented using pure types and functions. We have been discussing a lot with regard to how it can be done for our Blackjack game in the previous part of the book, so it should be easy for you to follow. Let’s create a file called Cards.hs in the src folder and put all the pure types and functions for the Cards problem domain that we have designed in the early chapters:

{-#LANGUAGE OverloadedStrings #-}

module Cards

where

-- simple algebraic data types for card values and suites

data CardValue = Two | Three | Four | Five | Six | Seven | Eight | Nine | Ten | Jack | Queen | King | Ace

  deriving (Eq, Enum)

data CardSuite = Clubs | Spades | Diamonds | Hearts deriving (Eq, Enum)

-- our card type - merely combining CardValue and CardSuite

data Card = Card CardValue CardSuite deriving(Eq)

-- synonym for list of cards to store decks

type Deck = [Card ]

instance Show CardValue where

  show c = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"] !! (fromEnum c)

instance Show CardSuite where

  show Spades   = "♠"

  show Clubs    = "♣"

  show Diamonds = "♦"

  show Hearts   = "♥"

-- defining show function that is a little nicer then default

instance Show Card where

  show (Card a b) = show a ++ show b

-- defining full deck of cards via comprehension; how cool is that?! :)

fullDeck :: Deck

fullDeck = [ Card x y | y <- [Clubs .. Hearts], x <- [Two .. Ace] ]

smallDeck :: Deck

smallDeck = [Card Ace Spades, Card Two Clubs, Card Jack Hearts]

dealCards :: Int -> Deck -> (Deck, Deck)

dealCards n deck = let newDeck = drop n deck

                       plDeck  = take n deck

                   in (newDeck, plDeck)

countCards :: Deck -> (Int, Deck )

countCards deck = (length deck, deck)

Here we have the types defined for representing our cards, a handy typeclass instance for Show typeclass so that our cards look nicer in the terminal output, and a couple of handy functions that deal and count the cards.

The {-#LANGUAGE OverloadedStrings #-} line at the top of our file defines various GHC options. GHC stands for “Glasgow Haskell Compiler” and is the most powerful and most developed Haskell compiler, even though there are others. It has many, many various extensions that come into the language directly from research papers, and many of them allow us to do some amazing stuff with types, but unfortunately we will only touch upon this topic very lightly – perhaps in more detail in a future book, as it deserves a book of its own. The “OverloadedStrings” option is the one you’ll likely use most often – it allows you to write code like

myString :: Text

myString = "Hello World"

Normally, it would not be allowed as literal strings in Haskell code must be of type String , which is just a synonym to very straightforward [Char] – list of chars – so you would have to provide explicit conversion from String to Text that gets tedious to write. Text on the other hand is a much more efficient implementation of packed strings with full Unicode support as well as other advantages – so whenever you want to work with text efficiently, you want to use Text . Unfortunately, a lot of useful libraries still use String for some functions, so you have to pay attention when writing production code. We’ll discuss this in more detail in the next chapters – especially the ones that deal with the Web.

The next lines define the name of our module – Cards – and eventually the list of imports, which is currently empty:

module Cards

where

The name of the module has to be the same as the file name, and it also follows the directory structure – if we created a folder called “Game” inside src and put “Cards.hs” there, the name of the module would have to be Game.Cards. Very straightforward to follow.

You can also test your current types and functions by loading your project into the interactive ghci environment using another handy stack command:

stack ghci

...

Loaded GHCi configuration from ...

ghci> let (deck, myDeck) = dealCards 5 fullDeck

ghci> myDeck

[2♣,3♣,4♣,5♣,6♣]

ghci>

This command loads all the modules of your project with all necessary dependencies, which means you can interactively test all of your types and functions – extremely handy to experiment and find potential issues with your code and absolutely necessary when learning Haskell. A couple of very useful ghci commands are “:i” that displays information on pretty much anything in your program and “:t” that gives you type information:

ghci> :i String

type String :: *

type String = [Char]

      -- Defined in 'GHC.Base'

ghci> :t myDeck

myDeck :: Deck

ghci> :i Deck

type Deck :: *

type Deck = [Card]

       -- Defined at .../ch08/src/Cards.hs:14:1

Feel free to explore a bit.

Now, what is missing from our small pure world of the Cards problem domain for our simplified Blackjack game? Of course , this is some data types to keep track of the “global” state for the player, which in our game is simply the amount of money, as well as the “local” state for hands for both the player and the dealer.

EXERCISE

Design these types and related useful functions and extend Cards.hs, respectively. For instance, calculating the Blackjack score of the hand function is currently missing!

Designing the types for the states as well as functions that calculate card and hand values is relatively straightforward, so let’s add the following code to our Cards.hs file. Some explanations are given in the comments, so read the listing carefully:

-- another type synonym for list of cards to provide additional clarity in the types below

type Hand = [Card]

-- state for the player

data Player = Player {

    playerHand :: Hand

  , playerBet :: Int

  , playerMoney :: Int } deriving Show

-- state for the dealer

data Dealer = Dealer { dealerHand :: Hand } deriving Show

-- convenience functions that extract rank and suit from any Card

rank :: Card -> CardValue

rank (Card r _) = r

suit :: Card -> CardSuite

suit (Card _ s) = s

-- Calculate the blackjack value of card. Ace is tricky!

cardValue :: Card -> Int

cardValue (Card rank _) = case rank of

    Ace -> 11  -- We'll handle Ace's 1 or 11 value in handValue

    Jack -> 10

    Queen -> 10

    King -> 10

    _ -> fromEnum rank - fromEnum Two + 2

-- Calculate the value of a hand . This function is not entirely correct, pay attention :)

handValue :: Hand -> Int

handValue hand =

    let baseValue = sum $ map cardValue hand

        aces = length $ filter (\c -> rank c == Ace) hand

    in if baseValue > 21 && aces > 0

       then sum $ map (\c -> if rank c == Ace then 1 else cardValue c) hand

       else baseValue

The function that calculates the hand value – handValue – is a bit tricky, but with the knowledge you have by now, you should decipher it easily. First, we are calculating baseValue by mapping over all cards in the hand and getting their face values. Then, if the resulting value is over 21 and we have Aces in the hand, we recalculate by making all Ace values equal to 1. Do you see where the problem is?

FIX THE ACES PROBLEM

Fix the handValue function so that it calculates the value of multiple Aces correctly. Alternatively – and if you are really into cards – expand the final program to give the player the ability to “split” their hand if they get two Aces.

Load the new code into ghci with stack ghci program and test the new functions.

The only missing piece in our pure Cards world is the overall state of the game that should combine all our “smaller” states. Here it is:

data GameState = GameState

    { player :: Player

    , dealer :: Dealer

    , deck :: Deck

    } deriving Show

This state type captures everything we need to keep track of in our game: player state, dealer state, and the state of the game deck. We could have easily made a game deck part of the Dealer since it is kind of a dealer’s deck, but this is a free design choice – you can do it differently just as easily.

The above gives us a solid pure foundation, and now we can move to constructing our monad stack so that we are able to handle the effects – randomizing decks, changing state, handling input/output!

Building the First Floor: IO

We have agreed that we will use a very simple monad stack for our program – StateT on top of IO . The goal of this chapter is to learn the principles, and expanding them to more layers or “floors” is very straightforward. But before we move to actual code, let us once again review Figure 8-1 that shows the high-level architecture of our program. We have a pure world that deals with modeling the problem domain and most of the internal business logic and a stack of two monads: State to update the game’s state and IO to interact with the player. Our next task is to continue designing types and functions, now related to our monad stack, but a very important step in this process is deciding which functions should live on which floors.

Let’s take a function of shuffling the deck as an example. We cannot implement it in the pure world, because it involves randomness, and randomness is provided in the IO monad. However, since our “final” program monad will be StateT on top of IO, we may want to run lots of functions, including shuffling the deck, directly there. If you recall in the last chapter, we have “lift” and “liftIO” functions that can help us with that. Also recall that functions from the lower floors of the monad stack can be lifted to the higher floors, but functions from the higher floors cannot be brought down to the lower floors . This gives us an important principle :

If a function needs to work on several “floors” of your monad transformer stack, always put it to the lowest possible level. That is, if a function can be pure, make it pure – that’s the most important principle – and then you can use it anywhere. If a function needs IO, but doesn’t need State, put it into IO. And so on.

With that, let’s start building our IO floor. Create a file called IOFloor.hs (of course this name is somewhat cheesy – feel free to change it to whatever suits your architectural design tastes best), and let’s put this initial code there:

{-#LANGUAGE OverloadedStrings #-}

module IOFloor

where

import System.Random

import Data.List (sortOn)

import Cards

shuffleDeck :: Deck -> IO Deck

shuffleDeck deck = do

    gen <- newStdGen

    return $ map snd $ sortOn fst $ zip (randoms gen :: [Int]) deck

In order for it to compile when you run stack build , you will need to add an explicit dependency on random package to package.yaml:

dependencies:

- base >= 4.7 && < 5

- random

This is the usual pattern if you want to use an external library – you import what you need in the import statements of your source code and then add a dependency to the package to package.yaml. In some cases you may need to give some additional info, such as versions, or reference to an external source and others, but stack is usually very helpful in providing messages that guide you through that process. In this book further on, let’s focus on code.

Another notable thing in this code is that it follows our design picture quite closely – we import the Cards module, which defines our pure functions and types, to use on the IO floor. But Cards itself does not import anything that has even the slightest thing to do with the IO, thus remaining independent and pure.

Once your code compiles, run stack ghci and test that our shuffling function works:

ghci> d <- shuffleDeck fullDeck

ghci> d

[4♠,A♣,3♣,A♥,5♠,4♣,Q♥,10♣,2♣,Q♠,7♠,8♠,5♣,5♥,J♦,10♥,5♦,4♥,3♠,2♦,6♠,2♥,J♠,4♦,8♦,K♥,7♣,A♠,9♠,K♠,2♠,6♣,Q♦,9♣,Q♣,8♥,J♥,K♣,6♦,7♥,9♥,10♦,3♦,A♦,3♥,10♠,K♦,6♥,9♦,7♦,J♣,8♣]

ghci>

Now, why did we write d <- shuffleDeck fullDeck instead of let d = … ? Think and answer before reading further.

If you look at the type of our shuffling function, it says Deck -> IO Deck . This means it is a computation in the IO monad that “returns” the value of type Deck, but lifted in the IO monad. And if you read the last chapter carefully, you know that there is no escaping the IO monad, but instead using so-called do notation , we can bind pure values to variables from IO computations – and this is exactly what we do here. Now that we have a “pure” Deck bound to the “d” variable, we can further inspect it inside ghci, for instance, by running handValue d to get 340 as the answer. Without the do notation we could have written something like shuffleDeck fullDeck >>= pure . handValue with the same effect. Dwell on it and re-read the last chapter if needed. These things may be confusing at first, but if you carefully look at the types, everything should become clear.

But why did we make our shuffleDeck function an IO computation in the first place? To answer that, go to hackage.haskell.org, search for System.Random, and let’s read the docs for newStdGen (Figure 8-3 ).

The image shows a code snippet for the function `newStGen` in Haskell. It indicates that `newStGen` is a function with type signature `MonadIO m => m StdGen`. The description explains that it applies `split` to the current global pseudo-random generator `globalStdGen`, updates it with one of the results, and returns the other. The function has been available since version 1.0.0.

Figure 8-3

Documentation for newStdGen

The type signature tells us that it’s a monadic action in some monad m that is part of the MonadIO typeclass. The latter is a very handy method to generalize library methods to custom monads using IO under the hood, but we won’t get into it now. What we need to know is that IO itself is indeed part of MonadIO. So the only way for us to work with random numbers (apart from writing a pure pseudo-random generator yourself – might be possible, but not very practical as it will be fully deterministic by definition) is by being inside IO. Hence, we have to make the shuffling function an IO computation. Haskell’s type system forces us to make certain decisions, but these decisions protect the purity and guarantees of the language.

I leave decoding of what the function actually does to the reader – it’s a good exercise that you can easily do by now. The only missing piece there is the randoms function, which is also part of System.Random – so read on it while you are on Hackage. To give you a hint, zip … creates a list of tuples, where each tuple contains a random integer and a card from the deck. The rest is just some basic list manipulation.

What other functions do we need on our IO floor? Of course, those are functions that get input from the user and show the current state of the hands and money to the user.

EXERCISE

Design and write the remaining functions that should live on the IO “floor” of our monad stack.

Once you are done, you can check how we have implemented it in the repository code, and let’s move to the top floor of our stack – the actual Game monad, built as StateT on top of IO.

Building the Top Floor: StateT IO

Create another file called GameFloor .hs in the src folder, and let’s build the top floor for the monad stack of our game:

{-#LANGUAGE OverloadedStrings #-}

module GameFloor

where

import Control.Monad.State

import Cards

-- Our monad transformer stack

type Game = StateT GameState IO

For this to compile, you need to carefully write all imports and then add mtl to the list of dependencies in package.yaml just as we did with random previously. We are using the mtl library here, even though we could have used transformers . Feel free to familiarize yourself with both, but the important thing to keep in mind is that mtl is built on top of transformers and provides some additional handy features.

The most important line in the code above is of course the definition of the Game type: type Game = StateT GameState IO. It tells us that Game is a State monad transformer with state represented by GameState, which we defined above, and living on top of the IO monad. It literally recreates the scheme in Figure 8-1 in the very beginning of this chapter. Game is also a monad itself, as any monad transformer stack, so we can apply everything we learned about monads and the State monad in particular in the previous chapters.

For instance, it means that inside any Game computation, we can write get >>= or state <- get (using do notation) and get access to the current state (that will be of type GameState), while we can also use liftIO to run any IO computation. That’s basically it. That’s pretty much all we need to know to finish our program! But of course I encourage you to read the docs for the State monad in the mtl library, as usual – learning key libraries is essential to becoming a high-performing Haskell programmer. They are like the spell books for magicians! The more you know, the more powerful you become.

Now we can design the actual game logic, using pure types and functions from Cards and IO types and functions from the IO floor of our stack. The game goes as follows:

  • The player bets.

  • The dealer deals two cards to the player and one to themselves .

  • We show all cards to the player.

  • The player either “hits” – and is dealt another card until they go bust – or says “stop.”

  • The dealer takes cards until they either hit 17 or more or go bust.

  • We adjust the player’s balance according to who won.

BUILD THE GAME FUNCTIONS

Build the computations in the Game monad that implement the functionality described above. As you are working on this, you may have ideas on how to expand the pure Cards.hs world to make your life easier as a programmer building the rest of the game. One example can be a function that modifies the player status in such a way that we either add or take some money to or from their account. What other examples are there? Expand the pure world – and remember the principle: if a function can be made pure, it should.

Let us build all these functions one by one, expanding our pure and IO worlds and floors as we go. The following is a very detailed walk-through of an actual typical design approach to writing Haskell programs – we will not be as detailed in the next chapters of this book, but the principles learned here will help you fill the gaps in more advanced concepts.

Start of the round: a player bets . We need to ask the player how much, decrease their account correspondingly, and proceed further. We can implement this function fully inside Game, but we remember the principle discussed above – the computations should be put as low in the stack as possible. Applying this principle together with the idea of decomposing the problem into easier pieces, we decide that a much better design is to have two functions: a first in IO that asks the player for their bet and returns a number and a second in Game that adjusts the player’s status, respectively. Further thinking through this, we decide to add a third, pure function, makeBet, that makes code much more readable. This design is cleaner, easier to maintain, and more general!

Here are the code changes:

-- IOFloor.hs

...

import Text.Read (readMaybe)

...

-- get a bet number from the player

getPlayerBet :: IO Int

getPlayerBet = do

    bet <- do

        putStrLn "Enter your bet (min: 10, max: 100):"

        readMaybe <$> getLine

    case bet of

        Just b | b >= 10 && b <= 100 ->

            pure b

        _ -> do

            putStrLn "Invalid bet. Please try again."

            getPlayerBet

-- Cards.hs:

-- convenience pure function modifying player state after making a bet:

makeBet :: Int -> Player -> Player

makeBet bet pl = pl { playerBet = bet, playerMoney = (playerMoney pl) - bet}

-- GameFloor.hs:

...

-- initial game state

initialState :: GameState

initialState = GameState

    { player = Player [] 0 1000

    , dealer = Dealer []

    , deck = fullDeck

    }

-- computation in Game that asks a player for a bet and makes needed state adjustments

playerBetAction :: Game ()

playerBetAction = do

    bet <- liftIO getPlayerBet

    pl <- gets player

    let pl' = makeBet bet pl

    modify (\s -> s { player = pl'})

Some comments to the above. The getPlayerBet IO function can be improved by using a function such as maybe that we briefly mentioned in the early chapters, but the current code even though a bit clumsy is easier to read. Also, you may note that min and max bets are now hardcoded – a bad design – and an obvious improvement is to add some read-only game settings and manage them by using which abstraction? Of course, the Reader monad! That will be a nice exercise to improve the current game, won’t it?

The first computation from the Game floor – playerBetAction – uses getPlayerBet to get a number from the player and then makes necessary adjustments to the state. It uses everything we’ve discussed so far about state transformers – lifting a function from IO to our higher floor with liftIO, getting the current state via gets, adjusting it with the help of a handy pure function, and then modifying the game state with the help of modify (read the documentation for the State monad from the mtl library to understand what other functions are available), which puts a new player state into our GameState. Very concise code for so many things happening!

You may also notice that we don’t check whether the user is betting more than they have left. You guessed it right – another good exercise ☺

As usual, you can test the functions we just added in ghci by running stack ghci and then

ghci> execStateT playerBetAction initialState

Enter your bet (min: 10, max: 100):

300

Invalid bet. Please try again.

Enter your bet (min: 10, max: 100):

50

GameState {player = Player {playerHand = [], playerBet = 50, playerMoney = 950}, dealer = Dealer {dealerHand = []}, deck = [2♣,3♣,4♣,5♣,6♣,7♣,8♣,9♣,10♣,J♣,Q♣,K♣,A♣,2♠,3♠,4♠,5♠,6♠,7♠,8♠,9♠,10♠,J♠,Q♠,K♠,A♠,2♦,3♦,4♦,5♦,6♦,7♦,8♦,9♦,10♦,J♦,Q♦,K♦,A♦,2♥,3♥,4♥,5♥,6♥,7♥,8♥,9♥,10♥,J♥,Q♥,K♥,A♥]}

ghci>

execStateT is another function from the State monad standard interface – it takes a StateT action (which in our case is a Game action) and initial state, runs the action, and returns final state. As you can see, our code runs correctly – a 50 bet is being correctly shown in the final state.

Let’s continue building our Game floor!

The dealer deals two cards to the player and one to themselves . To deal n cards to the player , we have to do a bunch of different GameState manipulations that are very straightforward:

dealCardsToPlayer :: Int -> Game ()

dealCardsToPlayer n = do

    -- read current GameState

    gs <- get

    let pl = player gs

    -- deal cards using pure function

    let (newDeck, playerDealt) = dealCards n (deck gs)

    -- create new player status with new cards

    let pl' = pl { playerHand = (playerHand pl) ++ playerDealt }

    -- update game status

    modify (\s -> s { player = pl', deck = newDeck})

This should be easy to follow. We are using the pure functions we have already defined and then updating different states step by step. This code can be optimized quite a bit, plus a function that deals to the dealer repeats a lot of it, so making the two computations more concise is another nice exercise for you.

Show all (currently dealt) cards to the player . Again, also very straightforward:

showPlayerState :: Game ()

showPlayerState = do

    pl <- gets player

    liftIO $ print pl

Same for the dealer’s hand.

Rounds of the player hitting or stopping, then the dealer takes his cards, and then we determine the round winner . This functionality combines what we’ve defined before into some sort of a round loop:

-- GameFloor.hs:

-- part when the dealer takes cards

-- we are passing the final player hand score to compare

dealerAction :: Int -> Game ()

dealerAction pvalue = do

    dl <- gets dealer

    let value = handValue (dealerHand dl)

    if value < 17

        then do

            dealCardsToDealer 1

            showDealerHand

            dealerAction pvalue

        else do

            showDealerHand

            liftIO $ putStrLn $ "Dealer stands with " ++ show value

            if ((value > 21) || (value < pvalue))

                then do

                    liftIO $ putStrLn "Player wins!"

                    pl <- gets player

                    let pl' = payout ((playerBet pl)*3) pl

                    modify (\s -> s {player = pl'})

                    showPlayerState

                else do

                    liftIO $ putStrLn "Player looses :("

                    pl <- gets player

                    let pl' = payout 0 pl

                    modify (\s -> s {player = pl'})

                    showPlayerState

-- main player round

playerAction :: Game ()

playerAction = do

    showDealerHand

    showPlayerState

    action <- liftIO $ do

        putStrLn "Do you want to (H)it or (S)tand?"

        getLine

    case action of

        "H" -> do

            dealCardsToPlayer 1

            pl <- gets player

            let newValue = handValue (playerHand pl)

            if newValue > 21

                then do

                    liftIO $ putStrLn "You bust!"

                    showPlayerState

                    let pl' = payout 0 pl

                    modify (\s -> s {player = pl'})

                    showPlayerState

                    -- modifyPlayer player (\p -> p { playerMoney = playerMoney p - playerBet p })

                else if newValue == 21

                    then do

                        liftIO $ putStrLn "21! Paying out 2x!"

                        showPlayerState

                        let pl' = payout ((playerBet pl)*3) pl

                        modify (\s -> s {player = pl'})

                        showPlayerState

                    else playerAction

        "S" -> do

            showPlayerState

            liftIO $ putStrLn "You stand"

            pl <- gets player

            let newValue = handValue (playerHand pl)

            dealerAction newValue

        _ -> do

            liftIO $ putStrLn "Invalid action. Please choose H or S."

            playerAction

-- Cards.hs:

-- another helper function

payout :: Int -> Player -> Player

payout amount pl = pl { playerBet = 0, playerMoney = (playerMoney pl) + amount, playerHand = [] }

The code above is purposely made very verbose and straightforward. There is a lot of room for optimization using usual Haskell techniques: you can add several helper functions, both pure and in the Game monad, such as modifying the player’s state within the Game monad; you can optimize the branching using guards and similar techniques; etc. Try that before we finish the program.

EXERCISE

Optimize the playerAction and dealerAction methods above.

All that is left by now is to implement the main game cycle, where we shuffle the deck between rounds , ask a player for the bet, and then run the player round.

Final Game and Recap

The final computation that is left to add is the main game cycle:

gameCycle :: Game ()

gameCycle = do

    -- asking for a bet first

    playerBetAction

    d <- gets deck

    -- checking if the deck has fewer than 15 cards left

    if (length d) < 15

        then do

            -- if yes, resetting to full deck

            modify (\s -> s {deck = fullDeck})

            gameCycle

        else do

             -- shuffling the deck first

            d' <- liftIO $ shuffleDeck d

            modify (\s -> s {deck = d'})

             -- dealing cards

            dealCardsToPlayer 2

            dealCardsToDealer 1

             -- cycling game rounds

            playerAction

             -- resetting the dealer’s hand

            dl <- gets dealer

            modify (\s -> s { dealer = dl {dealerHand = []}})

            gameCycle

The code above is also prone to a couple of small optimizations, such as moving the dealer hand reset code to the main round cycle and others. In any case, by now we have fully finished building the Game floor, which is “just” a StateT GameState IO monad transformer stack. The only thing that’s left is to define our “main” function in the Main.hs file:

{-# LANGUAGE OverloadedStrings #-}

module Main where

import Control.Monad.State

import GameFloor

main = execStateT gameCycle initialState

Our main computation is extremely simple: we run the gameCycle action with initialState with the help of the execStateT function from the State monad library interface that we discussed above. That’s it. We are done! You can build the program, run stack exec blackjack , and test that everything works:

{1:59}~/dev/magicalhaskell/ch08:main ✗ ➭ stack exec blackjack

Enter your bet (min: 10, max: 100):

100

Dealer {dealerHand = [J♠]}

Player {playerHand = [5♣,Q♦], playerBet = 100, playerMoney = 900}

Do you want to (H)it or (S)tand?

S

Player {playerHand = [5♣,Q♦], playerBet = 100, playerMoney = 900}

You stand

Dealer {dealerHand = [J♠,7♦]}

Dealer {dealerHand = [J♠,7♦]}

Dealer stands with 17

Player looses :(

And so on. The only last comment I’d like to make is let’s take one final look at the execStateT function, which has the following type: Monad m => StateT s m a -> s -> m s . May seem scary, but since we’ve long learned how to properly read Haskell type signatures, we can easily decode. In our Blackjack program StateT s m a stands for StateT GameState IO a, s stands for GameState, and m s is then simply IO GameState. This tells us that execStateT expects an action in any monad stack where StateT is on top and an initial state – and then executes this action and returns final state wrapped in the underlying monad . This is very important to remember – if you have a stack that has several monads, you’ll need to unwrap them using corresponding exec (and similar eval and run) methods. Read the docs for StateT, and then you will easily handle Reader and Writer in the same fashion.

IMPROVE BLACKJACK

There is a lot of room for improvement in the current Blackjack implementation. Think of what those can be and implement at least some of them. To get you started:

  • Various “don’t repeat yourself” optimizations.

  • Various checks – for the player’s balance and others.

  • Add Reader and Writer monads to the stack for better configuration and player notification functionality.

  • Add a multiplayer.

The key ideas that we tried to convey by building this simplified Blackjack program from scratch have to do mainly with the approach to designing and building Haskell programs. Let us review them once again – they are absolutely key in making you not just a “coder,” but a highly intelligent Haskell developer, who writes code that is easy to read and maintain:

  • Design the problem domain using pure types and functions first as much as possible.

  • Identify which monads you want to include in the stack of the final program, with State, Reader, Writer, and IO as the usual suspects.

  • Build each “floor” of the monad transformer stack separately, using the “the lower the function can live, the better” principle. Remember that lower functions can be lifted, while higher-floor functions are inaccessible from the lower floors.

  • As you are building the “floors,” expand the pure foundation as well as helper functions from the lower floors to your current one to help your code be more concise and maintainable .

  • Connect everything together in the “main” function using a hierarchy of “exec” or “eval” functions from monadic interfaces.

This design pattern, while quite simple, is extremely powerful and can be used to create applications of significant complexity and production quality. With this, we are finishing the first, mainly educational, part of the book and moving to more advanced concepts that we will review with specific practical examples using the principles we have learned so far. Hopefully, it can strengthen the Haskell foundation we built by now and make you fluent in analyzing any new abstractions and approaches you may face on your Haskell journey!

Conclusion

In this chapter, we've embarked on a comprehensive journey to design and implement a simplified Blackjack game using Haskell. This exercise has not only reinforced our understanding of Haskell's functional programming paradigms but also demonstrated the practical application of monads and monad transformers in structuring complex programs.

Key takeaways from this chapter include

  • Domain modeling with pure types and functions: We began by modeling our problem domain using pure types and functions. This foundational step ensures that our core logic is both reliable and testable, free from side effects.

  • Monad transformer stack design: We explored the design of a monad transformer stack, specifically using StateT over IO, to manage state and side effects. This approach allows us to cleanly separate pure logic from impure operations, maintaining the integrity of our functional design.

  • Layered architecture : By organizing our program into distinct layers or “floors,” we ensured that each component of our application is responsible for a specific aspect of the program's functionality. This modularity enhances readability, maintainability, and scalability.

  • Leveraging Haskell libraries: Throughout the chapter, we utilized Haskell's rich ecosystem of libraries, such as mtl and random, to handle common tasks efficiently. Understanding these libraries and their documentation is crucial for effective Haskell development.

  • Iterative development and testing : We emphasized the importance of iterative development, using tools like ghci for interactive testing. This practice helps catch errors early and refine our approach as we build complex systems.

  • Opportunities for enhancement: While we implemented a basic version of Blackjack, we identified numerous opportunities for improvement, such as adding more game features, optimizing code, and expanding the monad stack with additional layers like Reader and Writer.

By following these principles and practices, we've not only built a functional Blackjack game but also laid a strong foundation for tackling more complex Haskell projects. As we move forward in the book, we'll delve into advanced concepts and real-world applications, applying the design patterns and techniques we've mastered here.

Footnotes

1

Monad transformer stacks are not the only possible abstraction to structure Haskell programs, but certainly are the most common. It is always good to start with it and then move to more esoteric approaches, for instance, possible with Arrows.