如何在Elm中洗牌?

时间:2017-02-13 15:39:26

标签: elm

让我说我有一个包含数字1到5的列表。如何在Elm中编写一个名为shuffleList的函数,使得它将整数列表作为参数并返回随机版本列表?

如,

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

可以对随机种子进行硬编码

2 个答案:

答案 0 :(得分:8)

您可能需要来自elm-community / random-extra的shuffle函数。在Ellie

上使用它的示例

如果您想手动执行此操作,但在给定初始Seed的情况下,您可以执行以下操作(这会使用elm-community/list-extra包中的某些功能)

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"

Ellie

上使用此示例

答案 1 :(得分:0)

http://package.elm-lang.org/packages/elm-community/elm-random-extra/1.0.2有Random.Array.shuffle所以只需转换为数组,随机播放并转换回来

相关问题