Created
March 11, 2016 16:42
-
-
Save hoelzro/a49d796f2812714ec371 to your computer and use it in GitHub Desktop.
List shuffle implementation in Elm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Random exposing (Generator) | |
extractValueHelper : List a -> Int -> List a -> (a, List a) | |
extractValueHelper values index accumulator = | |
case (index, values) of | |
(_, []) -> Debug.crash "Out of values to extract" | |
(0, (head::tail)) -> (head, List.append (List.reverse accumulator) tail) | |
(_, (head::tail)) -> extractValueHelper tail (index - 1) <| head :: accumulator | |
extractValue : List a -> Int -> (a, List a) | |
extractValue values index = extractValueHelper values index [] | |
shuffle : List a -> Generator (List a) | |
shuffle values = | |
case values of | |
[] -> Random.map (\_ -> []) Random.bool | |
values -> | |
let randomIndexGenerator = Random.int 0 <| (List.length values) - 1 | |
extractAndRecurse = \index -> | |
let (randomHead, remainder) = extractValue values index | |
remainderGen = shuffle remainder | |
in Random.map (\randomTail -> randomHead :: randomTail) remainderGen | |
in Random.andThen randomIndexGenerator extractAndRecurse |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment