[Haskell] Re: About Random Integer without IO

karczma karczma at info.unicaen.fr
Thu Nov 11 15:58:40 EST 2004

Georg Martius answers the request of:
Jose Manuel Hernando Cobeña
>> I need generate random numbers by create polygons with "wxHaskell",
>> I am searching in the web, but all I only find IO functions like
>>>> test :: Integer -> IO Integer
>> I need this but with types :: Integer -> Integer

> you need to reallise that Haskell is a pure language. That means a 
> function has the same result if you call it with the same arguments 
> (deterministic). A function that produces random numbers are not of such 
> kind in the first place.

All depends on how you organize your computations. 

1. You may in a purely functional, non-monadic way produce an infinite
  list, a stream of numbers, and use them as you wish, incrementally. 

  gener seed =(aaa*seed + ccc) `mod` mmm     -- or something alike...
  strm = st seed0 where
    st x = x : st (gener x) 

  Eventually, you can directly pass the updated seed from one function to
  another in your program. In two words, write your programs in CPS, or
  a little 'monadized' style.
  Of course, you can transform the result from an integer between 0 and
  mmm-1 to other thing. 

2. Despite what G. Martius says, you CAN USE a pure, deterministic function
  to produce something which looks randomly, it suffices to change the
  argument. Concretely, Ward in Graphics Gems, and other people in other
  places propose 'chaotic', *ergodic* functions, which vary wildly from
  arg to arg, even neighbouring.
  This is a "kind of hashing function".
  An example can be found in this tutorial

  You take an integer, and mix its bits by taking xors, modulo,
  polynomials, etc.
  Then, such a function sampled for j=0,1,2,3, ... N will look like
  a genuinely random signal, without any need to 'propagate' anything. 

Jerzy Karczmarczuk 

PS. Georg Martius concludes:
> PS: this question is more appropriate for haskell-cafe. 

Well, why not haskell-bratwurst-mit-pils?  The protocol of making/using
random stuff within Haskell is a specific problem which is not very well
developed nor taught, but it is not anecdotical, it may be important. 

More information about the Haskell mailing list