-
Notifications
You must be signed in to change notification settings - Fork 0
/
cards.hs
48 lines (38 loc) · 1.48 KB
/
cards.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
-- Simple cards utility modules written in Haskell, all for fun
module Cards where
import System.Random
data Suit = Club | Diamond | Heart | Spade
deriving (Eq, Ord, Show, Read, Enum, Bounded)
data Rank = Two | Three | Four | Five | Six | Seven | Eight | Nine | Ten | Jack | Queen | King | Ace
deriving (Eq, Ord, Show, Read, Enum, Bounded)
data Card = Card Suit Rank
deriving (Show, Read)
instance Eq Card where
Card sa ra == Card sb rb = (sa == sb) && (ra == rb)
instance Ord Card where
compare (Card a b) (Card x y) | b < y = LT
| b == y && a < x = LT
| b == y && a == x = EQ
| b > y = GT
| b == y && a > x = GT
instance Bounded Card where
minBound = Card minBound minBound
maxBound = Card maxBound maxBound
instance Enum Card where
fromEnum (Card s r) = (fromEnum r) * 4 + (fromEnum s)
toEnum a =
Card (toEnum x) (toEnum y)
where
x = a `mod` 4
y = (a - x) `div` 4
type Deck = [Card]
makeDeck :: Deck
makeDeck = [minBound .. maxBound]
shuffle :: (RandomGen r) => r -> [x] -> [x]
shuffle gen a = shuffle' gen a []
where
shuffle' _ [] shuffled = shuffled
shuffle' g a shuffled =
let (k, g') = randomR (0, length a - 1) g
(h, x:xs) = splitAt k a
in shuffle' g' (h ++ xs) (x:shuffled)