How to shuffle a List in Elm?

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

Tags:

Elm