Introduction to Functional Programming – Lab 2: “Blackjack” | TDA555 / DIT440, LP1 2017 |
Home | Schedule | Labs | Lectures | Exercises | Exam | About | FAQ | Fire | WaitList | Group | TimeEdit | YouTube | Links |
Introduction to Functional Programming – Lab 2: “Blackjack” | TDA555 / DIT440, LP1 2017 |
Home | Schedule | Labs | Lectures | Exercises | Exam | About | FAQ | Fire | WaitList | Group | TimeEdit | YouTube | Links |
Some notes:
Remember that you have to work in groups of 3. Groups of size 2 can only submit with prior permission. Submissions by only 1 person or more than 3 persons are not allowed.
When you are done, please follow the submission instructions. Important: After the submission deadline you are required to present your solutions as a group to your grader. This will be either on the day of the submission or the day after, depending on your grader. To arrange this you will need to book a presentation slot. This is detailed on the lab overview page and/or the course home page.
Good luck!
In this lab assignment, you will write an implementation of (a simple variant of) the game Blackjack.1 By doing so you will learn how to work with lists using recursive functions and list comprehension. Since you have not really learned how to write programs which interact with the user (so-called input-output), we provide you with a “wrapper” module which takes care of those things for you.
The lab assignment is divided into 2 parts:
There are also some extra assignments mentioned after Task J. These are not obligatory, but you will learn more when you do them!
This lab assignment has 3 deadlines (2017):
The game you will implement is a simple variant of Blackjack. This section describes the rules that you should implement. We expect your implementation to follow these rules.
There are two players, the “guest” and the bank. First the guest plays. She (he) can draw as many cards as she wants, as long as the total value does not exceed 21. When the guest has decided to stop, or gone bust (score over 21), the bank plays. The bank draws cards until its score is 16 or higher, and then it stops.
The value of a hand (the score) is the sum of the values of the cards. The values are as follows:
The winner is the player with the highest score that does not exceed 21. If the players end up with the same score, then the bank wins. The bank also wins if both players go bust.
For this lab, you need the two files Cards.hs and Wrapper.hs. You do not need to understand anything about the wrapper, but you have to understand most of Cards
. That module contains some definitions from the lectures; data types and Arbitrary
instances for playing cards. See the slides here. Note that in the slides a Hand is defined using a recursive datatype. In this lab we are going to keep things simpler by using a list instead.
Read through the file so that you know which types you are supposed to use.
We will represent a player’s hand as a list of cards ([Card]
). For clarity, we defined a type synonym Hand
and use it instead of [Card]
. We can define an example hand, consisting of the cards 2 of Hearts and Jack of Spades as a list with two elements as follows:
hand2 :: Hand
hand2 = Card (Numeric 2) Hearts : (Card Jack Spades : [])
A more readable way of defining the same hand is:
hand2 :: Hand
hand2 = [Card (Numeric 2) Hearts, Card Jack Spades]
Cards.hs contains a recursive function that computes the number of cards in a hand:
size :: Num a => Hand -> a
size [] = 0
size (card:hand) = 1 + size hand
It is basically the same as the standard function length
.
In order to understand how recursion over lists works, take some time to work with it before you continue. You can for instance execute size hand2
by hand, on paper. The result should be 2, right?
Task A. Execute the expression
Write this sequence of equations as a Haskell definition in the following manner:
Put this and all the assignments of this lab in a file called |
To help you we have included a couple of QuickCheck properties below. Your functions must satisfy these properties. If they do not, then you know that something is wrong. Testing helps you find bugs that you might otherwise have missed. Note that you also have to write some properties yourself, as indicated below.
The purpose of writing properties is three-fold:
So, to take maximum advantage of the properties, write them before you write the corresponding functions, or at the same time.
The code has to be documented. See the Cards.hs and Wrapper.hs modules to get an idea about what kind of documentation is expected of you. Try to follow these guidelines:
Similar arguments apply to documentation as for properties; write the documentation when you write your functions, not afterwards.
Write all code in a file called Blackjack.hs
. To make everything work, add the following lines at the top of the file:
module Blackjack where
import Cards
import Wrapper
This tells the Haskell system that the module is called Blackjack
, and that you want to use the functions and data types defined in Cards
and Wrapper
. Download Cards.hs and Wrapper.hs and store them in the same directory as Blackjack.hs
, but do not modify those files.
As usual, when using QuickCheck you need to first import it. However, it turns out that recent versions of QuickCheck define a function shuffle
whose name clashes with the function you are supposed to define in task H. To avoid this problem, you can import QuickCheck as follows:
import Test.QuickCheck hiding (shuffle)
If you get an error about shuffle here it probably means you have an older version of QuickCheck, in which case just comment out the hiding (shuffle)
part. If it cannot find QuickCheck then you probably installed the minimal version of the Haskell platform which comes without without QuickCheck. Install the full version instead, or if bandwidth is an issue, type cabal install QuickCheck
in a command window.
When working on the functions below, it is a good idea to make two definitions,
aCard1 :: Card
aCard1 = ... -- define your favorite card here
aCard2 :: Card
aCard2 = ... -- define another card here
so that you can use these cards to test your functions. Also, make a definition,
aHand :: Hand
aHand = ... -- a Hand with two Cards, aCard1 and aCard2
to test your functions that work on hands.
Task B. Implement a function that, given a hand, shows the cards in it in a nice format.
For example, Hint: Start by writing a function putStr (display aHand) .
|
Task C. Implement a function that, given a hand, calculates the value of the hand according to the rules given above.
Remember that the special rules for this lab state that all aces have the same value: they are either all 1 or all 11 depending on the total value of the hand. Hint: To write the |
Task D. Implement two more functions that are necessary in the game.
|
The remaining tasks belong to Part II of the lab.
In this part we will need to represent a deck of cards (the cards from which the hand is dealt). We could also represent the deck of cards as a list of cards, but if we do this it is easy to mix up a deck of cards with a hand. To prevent this kind of error we have introduced a new data type for a Deck.
Task E. You also need to define a function that returns a full deck of cards:
You could do this by listing all 52 cards, like we did with two cards above. However, that is very tedious. Instead, do it like this: Write a function that returns a list of all possible ranks, and a function that returns given all possible suits, and then combine their results. Remember that to turn a list of cards into a Deck you need to apply the constructor function Your
|
Task F. Given a deck and a hand, draw one card from the deck and put on the hand. Return both the deck and the hand (in that order):
If the deck is empty, report an error using
|
Hint: To return two values a
and b
as a pair, use the syntax (a, b)
. This syntax is also used for pattern matching on pairs:
first :: (a, b) -> a
first (x, y) = x
Task G. Given a deck, play for the bank according to the rules above (starting with an empty hand), and return the bank’s final hand:
To write this function you will probably need to introduce a helper function that takes the deck and the bank’s hand as input. To draw a card from the deck you can use
You can read more about |
Task H. Write a function that shuffles a Since Haskell functions are functions in the mathematical sense, they always give the same result if you give them the same argument. This means it is impossible to write a Haskell function that takes a deck of cards and returns a randomly shuffled deck! The way we will sidestep this problem is to define a function which takes two arguments, the deck to be shuffled (as second argument) and a parameter representing the “randomness” as an input. To understand how this will work, imagine that you want to take a random walk in a maze. Do this you are given really big stack of coins which have been randomly flipped and piled in a stack. Whenver you have to make a choice between going left or right you look at the coin at the top of the stack: heads (krona) and you go left, tails (klave) and you go right. But to make your walk random you must discard the top coin after you have used it. Assume that the stack is big enough that you never run out. Your path is a function of the coin stack that you had as input. You will implement a shuffle function is a similar manner. Instead of a stack of coins you will have a list of floating point numbers (type Define the function:
Note: See above about how to import QuickCheck without getting name clashes with the If you want a (small) challenge, try to implement Hint (Shuffling strategy) One way to shuffle the cards would be to pick an random card from the deck and put it on top of the deck, and then repeat that many times. However, how many times should one repeat? If one repeats 52 times, then the probability that the last card is never picked is about 36%. This means that the last card is often the same, which of course is not good. A better idea is to randomly pick a card from the deck and put it in a new deck, then pick another card and put it on top of the new deck, and so on. Then we know that we have a perfectly shuffled deck in 52 steps (given that the input list of numbers is perfectly random, which it is not). Remember of course that to “pick a random card” we will use the list of random values that shuffle gets as its first argument. Note that for both approaches we need a function that removes the n-th card from a deck. Hint (Simpler coding) As a practical hint, you will find it easier to define a helper function |
Task I. The function
|
You have barely touched upon input/output in the lectures, so we have to provide you with a wrapper that takes care of those things. All you have to do is to write the functions above, package them together (as explained below), and then call the wrapper with the package as an argument.
Task J. To “package up” these functions, write the following code:
(Note that To run the program, define
in your source file, load the file in GHCi, and run |
Best of luck!
The following is completely optional, but if you want to do more, there are many possibilities:
Most of the ideas above require that you program input/output (I/O) yourself. You have seen how to do simple I/O in the lectures. Use the Wrapper.hs module as a starting point.
Note that doing something extra will not directly affect your grade, but can of course be beneficial in the long run. Take care to do the compulsory part above before attempting something more advanced, though.
Write your answers/solutions in one file, called Blackjack.hs
. For each assignment, use Haskell comments to indicate what part of the file contains the answer to the assignment. For answers in natural language, you can use Swedish or English; write these answers also as Haskell comments.
Before you submit your code, clean it up! Remember, submitting clean code is Really Important, and simply the polite thing to do. After you feel you are done, spend some time on cleaning your code; make it simpler, remove unneccessary things, etc. We will reject your solution if it is not clean. Clean code:
Please do not submit the modules Cards.hs
and Wrapper.hs
(unless an extra assignment required you to make changes to them).
Once you have submitted, please arrange to present your solution to one of the course assistants according to the instructions on the lab overview page.
Good luck!
This lab is based on material by Nils Anders Danielsson, Koen Claessen, Hampus Ram, Andreas Farre, Sebastian Sylvan and Mary Bergman.↩