Elm Generator Int -> 列表 Int

Elm Generator Int -> List Int

我想从 Generator

中得到 List
intList : Generator (List Int)
intList =
    list 5 (int 0 100)

我现在如何从中获取列表?

您无法从 Generator 中获得随机列表,因为 Elm 函数始终是纯函数。获得列表的唯一可能是使用 命令.

命令是一种告诉 Elm 运行时执行一些不纯操作的方法。在您的情况下,您可以告诉它生成一个随机的整数列表。然后它将 return 返回该操作的结果作为 update 函数的参数。

要向 Elm 运行时发送生成随机值的命令,可以使用函数 Random.generate:

generate : (a -> msg) -> Generator a -> Cmd msg

你已经有Generator a(你的intList),所以你需要提供一个函数a -> msg。此函数应将 a(在您的情况下为 List Int)包装成 message.

最终代码应该是这样的:

type Msg =
    RandomListMsg (List Int)
  | ... other types of messages here

update : Msg -> Model -> ( Model, Cmd Msg )
update msg model = case msg of
    ... -> ( model, Random.generate RandomListMsg intList)
    RandomListMsg yourRandomList -> ...

如果您还不知道 messagesmodels,您可能应该先熟悉 Elm architecture .

您可以向 Random.step 提供您自己的种子值,这将 return 一个包含列表和下一个种子值的元组。这保持了纯度,因为当你传递相同的种子时,你总是会得到相同的结果。

Random.step intList (Random.initialSeed 123)
    |> Tuple.first

-- will always yield [69,0,6,93,2]

@ZhekaKozlov 给出的答案通常是如何在应用程序中生成随机值,但它在幕后使用 Random.step,当前时间用作初始种子。