elm

How to shuffle a List in Elm?


Let's say I have a list containing the numbers 1 through 5. How would I write a function in Elm called shuffleList such that it takes a list of integers as an argument and returns a randomized version of the list?

E.g.,

shuffleList [1,2,3,4,5]
{-5,1,2,4,3-}

It is OK to hardcode the random seed


Solution

  • You probably want the shuffle function from elm-community/random-extra. Example of using that on Ellie

    If you want to do this by hand though, given an initial Seed you can do the following (this makes use of some functions from the elm-community/list-extra package)

    import List.Extra exposing (getAt, removeAt)
    import Random exposing (Seed, int, step)
    
    shuffleList : Seed -> List a -> List a
    shuffleList seed list =
        shuffleListHelper seed list []
    
    
    shuffleListHelper : Seed -> List a -> List a -> List a
    shuffleListHelper seed source result =
        if List.isEmpty source then
            result
        else
            let
                indexGenerator =
                    int 0 ((List.length source) - 1)
    
                ( index, nextSeed ) =
                    step indexGenerator seed
    
                valAtIndex =
                    getAt index source
    
                sourceWithoutIndex =
                    removeAt index source
            in
                case valAtIndex of
                    Just val ->
                        shuffleListHelper nextSeed sourceWithoutIndex (val :: result)
    
                    Nothing ->
                        Debug.crash "generated an index outside list"
    

    An example using this on Ellie