mardi 23 mars 2021

How to remember previous random value in Haskell

I am writing a random walk program in Haskell. The basic idea is generating a series of points, randomly at first, then let these points move randomly to next positions and so on. However, I can't let the function iterate, because it can't remember the previous computed value. How to solve this ?

The following is the code I wrote. The problem is that every time it only starts moving from the positions I gave initially.

import Graphics.Gloss
import System.Random

draw :: IO ()
draw = animate FullScreen white (picture [(1,2),(2,5),(4,7),(3,3)])

picture :: [Point] -> Float -> Picture
picture origin num = pictures [translate x y (circle 10) | (x,y) <- randomNext (round num) origin]

randomNext :: Int -> [Point] -> [Point]
randomNext num origin = zipWith (\(x1,y1) (x2,y2) -> (x1+x2,y1+y2)) r origin
    where r = zip (oner num) (oner (num+1)) 
          oner n = take (length origin) $ randomRs (-5::Float,5) (mkStdGen n)



Aucun commentaire:

Enregistrer un commentaire