Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the `randoms` function in Haskell work?

Tags:

haskell

I'm following the Learn You A Haskell book to learn Haskell, and I am having trouble understanding the randoms function. The book defines the function as:

randoms' :: (RandomGen g, Random a) => g -> [a]  
randoms' gen = let (value, newGen) = random gen in value:randoms' newGen    

Now the way I see this function is that it calls itself recursively and appends the return value to the list value. What I don't understand is how the function returns because every time it just calls itself with a new random seed!

like image 710
1 -_- Avatar asked Dec 06 '25 18:12

1 -_-


1 Answers

I think the confusing part might be the use of : in the return value.

value:randoms' newGen 

This is a list, with the first item of value, and the rest of the list is what is returned by the recursive call to randoms' newGen.

What I don't understand is how the function returns because every time it just calls itself with a new random seed!

Because of laziness, it will only call itself if you try to access the second (or later) item of the returned list. This list isn't, and couldn't be in memory, at once. Lists in Haskell are more like recipes... until you try to access an element, Haskell doesn't try to work out what it is.

like image 136
Michal Charemza Avatar answered Dec 08 '25 15:12

Michal Charemza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!