gpt4 book ai didi

haskell - 如何阻止随机性渗透到 Haskell 中的代码中?

转载 作者:行者123 更新时间:2023-12-02 17:22:09 25 4
gpt4 key购买 nike

我正在尝试实现以下算法,详细信息为 here .

  1. Start with a flat terrain (initialize all height values to zero).

  2. Pick a random point on or near the terrain, and a random radius between some predetermined minimum and maximum. Carefully choosing this min and max will make a terrain rough and rocky or smooth and rolling.

  3. Raise a hill on the terrain centered at the point, having the given radius.

  4. Go back to step 2, and repeat as many times as necessary. The number of iterations chosen will affect the appearance of the terrain.

但是,一旦我必须在地形上选择一个随机点,我就开始挣扎。这个随机点被包装在一个 IO monad 中,然后沿着我的函数链向上传递。

我可以在某个点切断IO吗?如果可以,我如何找到该点?

以下是我的(损坏的)代码。我将不胜感激任何关于改进它/阻止随机性感染一切的建议。

type Point = (GLfloat, GLfloat, GLfloat)
type Terrain = [Point]

flatTerrain :: Double -> Double -> Double -> Double -> Terrain
flatTerrain width length height spacing =
[(realToFrac x, realToFrac y, realToFrac z)
| x <- [-width,-1+spacing..width], y <- [height], z <- [-length,-1+spacing..length]]

hill :: Terrain -> Terrain
hill terrain = hill' terrain 100
where hill' terrain 0 = terrain
hill' terrain iterations = do
raised <- raise terrain
hill' (raise terrain) (iterations - 1)
raise terrain = do
point <- pick terrain
map (raisePoint 0.1 point) terrain
raisePoint r (cx,cy,cz) (px,py,pz) =
(px, r^2 - ((cx - px)^2 + (cz - pz)^2), pz)

pick :: [a] -> IO a
pick xs = randomRIO (0, (length xs - 1)) >>= return . (xs !!)

最佳答案

该算法表示您需要迭代,并在每次迭代中选择一个随机数并更新地形,这可以视为生成随机点列表并使用此列表进行更新地形即迭代生成随机数==随机数列表。

所以你可以这样做:

selectRandomPoints :: [Points] -> Int -> IO [Points] -- generate Int times random points
updateTerrain :: Terrain -> [Points] -> Terrain

-- somewhere in IO
do
pts <- selectRandomPoints allPts iterationCount
let newTerrain = updateTerrain t pts

关于haskell - 如何阻止随机性渗透到 Haskell 中的代码中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19994920/

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