summaryrefslogtreecommitdiff
path: root/rain.bh.hs
blob: f7267f809a9cf1b1c9c8013de8eb46df6b403d09 (plain)
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#! /usr/bin/env nix-shell
#! nix-shell -p "haskellPackages.ghcWithPackages (pkgs: [pkgs.random])" -i runghc

{-# OPTIONS_GHC -Wall #-}

{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}

{-

Problem: Create a string array containing a representation of the 52 cards in a
standard deck, and then a second array that shuffles the 52 cards.

Start with two string arrays of the cards and suits:
Cards: 2, 3, 4, 5, 6, 7, 8, 9, 10, J, K, Q, A
Suits: Clubs, Diamonds, Aces, Spades

-}

import System.Random
import Control.Monad
import Control.Applicative

data Name
    = Two
    | Three
    | Four
    | Five
    | Six
    | Seven
    | Eight
    | Nine
    | Ten
    | Jack
    | King
    | Queen
    | Ace
    deriving (Show, Enum, Bounded)

names :: [Name]
names = [ Two .. ]

data Suit
  = Club
  | Diamond
  | Heart
  | Spade
  deriving (Show, Enum, Bounded)

suits :: [Suit]
suits = [ Club .. ]

type Card = (Name, Suit)

instance Random Suit where
    randomR (a, b) g =
        case randomR (fromEnum a, fromEnum b) g of
            (x, g') -> (toEnum x, g')
    random g = randomR (minBound, maxBound) g

instance Random Name where
    randomR (a, b) g =
        case randomR (fromEnum a, fromEnum b) g of
            (x, g') -> (toEnum x, g')
    random g = randomR (minBound, maxBound) g

-- Dot product is same as 'liftA2 (,)'
allCards :: [Card]
allCards = liftA2 (,) names suits

shuffle' :: [Card] -> _
shuffle' (i:is) xs = (last firsts) : shuffle' is (init firsts ++ rest)
    where (firsts, rest) = splitAt (i `mod` length xs) xs


shuffle g xs = shuffle (randoms g) xs

main :: IO [()]
main = do
    g <- getStdGen
    let namesLength = length names
    let randomNames = map fromEnum $ take namesLength $ randomRs (0, namesLength-1) g
    let suitsLength = length suits
    let randomSuits = map fromEnum $ take suitsLength $ randomRs (0, suitsLength-1) g
    sequence $ map (putStrLn.show) $ liftA2 (,) randomNames randomSuits