[Haskell-cafe] random number generators
paul at cogito.org.uk
Thu Mar 22 15:58:35 EDT 2007
david karapetyan wrote:
> hi, i have been trying to learn haskell and i would like to translate
> the following object-oriented pseudo-code into working haskell code
> but i'm stumped on how to write the next function in the haskell code.
> any help is appreciated.
> class Random
> ran = Random.new(300)
> ran.next() <- this call generates a random number
> ran.next() <- this one generates a different random number
> so far what i have in haskell is:
> data Random = Ran Int Int
> next :: Random->Int <- i have no idea how to write the next function
> that would give me the desired effect
> because the object in the
> object-oriented code can remember how many times 'next'
> was called and i would
> like to do the same for 'ran' in the haskell code.
> ran = Ran 300 0
> next ran <- this generates a random number
> next ran <- this generates another random number but since
> haskell is purely functional it is going to be the
> same as from
> the previous call of 'next' which is not what i want
Is this homework?
There is a chapter on random numbers in the Wikibook. You will find it
Are you trying to define your own random number generator, or use the
Your use of <- arrows seems to indicate you want to use code in a "do"
block (i.e. monadic code). This allows side effects to propagate. The
random number stuff has an interface to IO for this reason. The
Wikibook has the details.
For extra credit, define your own random monad rather than using IO.
Wrap a random generator in a State monad, and then write appropriate
functions to use the state. See "All About Monads" for an explanation
of the state monad.
More information about the Haskell-Cafe