如何获得信号确定范围内的随机值? [英] How can I get a random value in a range determined by a signal?

查看:64
本文介绍了如何获得信号确定范围内的随机值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

第一个代码:

import Random
import Window

writeRandom x = lift asText (Random.range 0 x <| every second)

upperLimit = 300
-- upperLimit = Window.width -- How can i use this instead?

main = writeRandom upperLimit

我最终试图获得随机点在屏幕上,但我不知道如何将Window.height和Window.width传递给Random.range。我认为我无法提升 Random.range,因为它已经返回了信号。如果我尝试输入类型错误:

Ultimately I'm trying to get random points on the screen, but I can't figure out how to pass Window.height and Window.width to Random.range. I don't think I can 'lift' Random.range, since it already returns a signal. If I try I get a type error:

Type Error: 'main' must have type Element or (Signal Element).
Instead 'main' has type:

   Signal (Signal Element)

而且我不确定是否存在提升(降低?)的对立面,甚至说不通。

And I'm not sure that the opposite of lift (lower?) exists, or even makes sense.

谢谢

推荐答案

您正确地认为lower的反义没有意义。

在这种特殊情况下,内置Random库是内置的因为它是原生JavaScript调用的包装。这就是 Signal 返回类型保持代码纯净的原因。即便如此,它仍然是行为不完善

You are correct in supposing that an opposite of lower doesn't make sense.
In this particular case, the builtin Random library is builtin because it's a wrapper around a native JavaScript call. This is the reason for the Signal return type, to keep the code pure. And even then, it's not completely well-behaved.

要获得所需的随机范围,您需要使用其他随机数生成器。仅在几天前发布了一个社区库,可能会满足您的需求。您可以自己从GitHub检出,或使用 elm-get 工具。

To get the kind of random range you want, you'll need a different random number generator. There is a community library that was published only a few days ago, that'll probably answer your needs. You can check it out of GitHub yourself, or use the elm-get tool.

您的代码将变为( unested!):

import Window
import Generator
import Generator.Standard as GStd

randomSeed = 12346789

writeRandom : Signal Int -> Signal Element
writeRandom x = 
  let update high (_, gen) = Generator.int32Range (0,high) gen
      start = (0, GStd.generator randomSeed)
      input = sampleOn (every second) x
      result = fst <~ foldp update start input
  in  lift asText result

upperLimit = Window.width

main = writeRandom upperLimit

writeRandom 中,您使用 foldp 保留最新的随机数生成器。在 update 中,您可以使用它来获取新的随机数和下一次的新生成器。通过使用 sampleOn(每秒)每秒更新一次 x 的输入。 fst<〜部分将删除随机数生成器,因为您只需要随机数。

In writeRandom, you use foldp to keep the latest random-number generator. In update you use this to get a new random number and a new generator for the next time. The input of x is updated every second by using sampleOn (every second). The fst <~ part is to remove the random number generator, since you only want the random number.

这篇关于如何获得信号确定范围内的随机值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆