Elm Generator Int -> List Int

Mih*_* L. 3 elm

我想List摆脱Generator

intList : Generator (List Int)
intList =
    list 5 (int 0 100)
Run Code Online (Sandbox Code Playgroud)

我现在怎么能从中得到一个列表?

Zhe*_*lov 5

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

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

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

generate : (a -> msg) -> Generator a -> Cmd msg
Run Code Online (Sandbox Code Playgroud)

你已经有了Generator a(你的intList),所以你需要提供一个函数a -> msg。这个函数应该aList 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 -> ...
Run Code Online (Sandbox Code Playgroud)

如果您还不了解消息模型,您可能应该首先熟悉Elm 架构