【发布时间】:2017-11-25 07:37:15
【问题描述】:
我想从Generator 中取出List
intList : Generator (List Int)
intList =
list 5 (int 0 100)
我现在怎么能从中得到一个列表呢?
【问题讨论】:
-
你不能因为返回 5 个随机数列表的函数不是纯函数。您能否详细说明您想要实现的目标,我们可以帮助您找到惯用的方法
标签: elm
我想从Generator 中取出List
intList : Generator (List Int)
intList =
list 5 (int 0 100)
我现在怎么能从中得到一个列表呢?
【问题讨论】:
标签: elm
您无法从Generator 中获取随机列表,因为 Elm 函数始终是纯函数。获取列表的唯一方法是使用命令。
命令是一种告诉 Elm 运行时执行一些不纯操作的方法。在您的情况下,您可以告诉它生成一个随机整数列表。然后它将该操作的结果作为update 函数的参数返回。
要向 Elm 运行时发送命令以生成随机值,可以使用函数Random.generate:
generate : (a -> msg) -> Generator a -> Cmd msg
你已经有了Generator a(你的intList),所以你需要提供一个函数a -> msg。此函数应将a(在您的情况下为List Int)包装成一个消息。
最终的代码应该是这样的:
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 -> ...
如果您还不了解 messages 和 models,您可能应该先熟悉 Elm architecture。
【讨论】:
Random.generate intList,这将如何打破pure function 的概念?
您可以将自己的种子值提供给Random.step,这将返回一个包含列表和下一个种子值的元组。这保持了纯度,因为当您传递相同的种子时,您将始终得到相同的结果。
Random.step intList (Random.initialSeed 123)
|> Tuple.first
-- will always yield [69,0,6,93,2]
@ZhekaKozlov 给出的答案通常是您如何在应用程序中生成随机值,但它在后台使用Random.step,并将当前时间用作初始种子。
【讨论】: