gpt4 book ai didi

random - Elixir - Agent 中的随机数

转载 作者:行者123 更新时间:2023-12-01 16:38:59 25 4
gpt4 key购买 nike

我正在尝试实现一个充当骰子的代理:

defmodule Dice do
@on_load :seed_generator

def start_link(opts \\ []) do
Agent.start_link(fn -> [] end, name: __MODULE__)
end

def roll(n, val) do
Agent.cast(__MODULE__, fn(_) ->
Stream.repeatedly(fn -> :random.uniform(val) end)
|> Enum.take(n)
end)
end

def seed_generator do
:random.seed(:erlang.now)
:ok
end
end

但是,每次我重新启动 iex 时,生成的数字都是相同的。我究竟做错了什么 ?种子不起作用是因为 :random.uniform 调用位于 Agent 内部吗?或者可能是与Stream相关的东西。

最佳答案

seed_generator 函数的调用过程与您的 Agent 所使用的过程不同。事实上,在加载此代码时该进程甚至不存在。尝试在启动 Agent 时为生成器播种:

defmodule Dice do
def start_link(opts \\ []) do
Agent.start_link(fn -> :random.seed(:erlang.now) end, name: __MODULE__)
end

def roll(n, val) do
Agent.get(__MODULE__, fn(_) ->
Stream.repeatedly(fn -> :random.uniform(val) end)
|> Enum.take(n)
end)
end
end

关于random - Elixir - Agent 中的随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30438670/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com