Skip to content

Instantly share code, notes, and snippets.

@hoelzro
Created March 11, 2016 16:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hoelzro/a49d796f2812714ec371 to your computer and use it in GitHub Desktop.
Save hoelzro/a49d796f2812714ec371 to your computer and use it in GitHub Desktop.
List shuffle implementation in Elm
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