Last active
February 13, 2017 15:07
-
-
Save AlexNisnevich/e3693d68ec3eeb7b23d6 to your computer and use it in GitHub Desktop.
Shuffling a list 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 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