Shuffling a deck of cards with Elm

Image for post
Image for post

Cutting the deck

> List.Extra.splitAt 3 [10, 11, 12, 13, 14, 15]
([10,11,12],[13,14,15])
cut : Int -> List a -> List a
cut j list =
let
k = modBy (List.length list) j
(a, b) = List.Extra.splitAt k list
in
b ++ a
> cut 3 [1,2,3,4,5,6,7,8]
[4,5,6,7,8,1,2,3]
> cut 3 ["Red", "Green", "Blue", "Black", "White"]
["Black","White","Red","Green","Blue"]

Shuffling the deck

> List.Extra.interweave [1,2,3] [4,5,6]
[1,4,2,5,3,6]
shuffle : List a -> List a
shuffle list =
let
(a, b) = List.Extra.splitAt ((List.length list)//2) list
in
List.Extra.interweave a b
> shuffle [1,2,3,4,5,6]
[1,4,2,5,3,6]
> shuffle [1,2,3,4,5]
[1,3,2,4,5]

Dealer’s move

dealersMove : Int -> List a -> List a
dealersMove k list =
list
|> cut k
|> shuffle
> dealersMove 2 [1,2,3,4,5,6]
[3,6,4,1,5,2]

Repeating the Dealer’s Move

randomizeList : (List Int) -> List a -> List a
randomizeList integerList list =
List.foldl dealersMove list integerList
randomizeList [2, 5] [1, 2, 3, 4, 5, 6, 7, 9, 10]
[10,3,6,7,1,4,2,9,5]

Appendix

module Cards exposing (..)

import List.Extra

cut : Int -> List a -> List a
cut j list =
let
k = modBy (List.length list) j
(a, b) = List.Extra.splitAt j list
in
b ++ a

shuffle : List a -> List a
shuffle list =
let
(a, b) = List.Extra.splitAt ((List.length list)//2) list
in
List.Extra.interweave a b

dealersMove : Int -> List a -> List a
dealersMove k list =
list
|> cut k
|> shuffle

{-|
> randomizeList [2, 4, 3] [1,2,3,4,5,6]
[4,5,3,6,1,2]
-}
randomizeList : (List Int) -> List a -> List a
randomizeList integerList list =
List.foldl dealersMove list integerList

Written by

jxxcarlson on elm slack, http://jxxcarlson.github.io

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store