Skip to content

Instantly share code, notes, and snippets.

@chrisbuttery
Forked from AlexNisnevich/shuffle.elm
Created May 19, 2016 05:08
Show Gist options
  • Save chrisbuttery/c37a9ad0ab9768c87ff7ab14edc9fbb9 to your computer and use it in GitHub Desktop.
Save chrisbuttery/c37a9ad0ab9768c87ff7ab14edc9fbb9 to your computer and use it in GitHub Desktop.
Shuffling a list in Elm
import List
import Random
without : Int -> [a] -> [a]
without i arr =
let before = take i arr
after = drop (i+1) arr
in
before ++ after
shuffle : [a] -> Signal b -> Signal [a]
shuffle list signal =
let randomsFromSignal signal = Random.floatList (lift (\x -> List.length list) signal)
shuffleWithRandoms list randoms =
if (List.isEmpty list)
then []
else
let i = floor (head randoms * toFloat (List.length list))
ith = head (drop i list)
in
[ith] ++ (shuffleWithRandoms (without i list) (tail randoms))
in
lift2 shuffleWithRandoms (constant list) (randomsFromSignal signal)
main : Signal Element
main =
lift asText (shuffle [1..60] (every second))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment