Random Numbers in PureScript
Here’s the translation of the Go code to PureScript, along with explanations in Markdown format suitable for Hugo:
module Main where
import Effect.Console (log)
import Effect (Effect)
import Effect.Random (randomInt, randomRange)
main :: Effect Unit
main = do
-- For example, `randomInt` returns a random Int n,
-- 0 <= n < 100.
n1 <- randomInt 0 99
n2 <- randomInt 0 99
log $ show n1 <> "," <> show n2
-- `randomRange` returns a Number f,
-- 0.0 <= f < 1.0.
f <- randomRange 0.0 1.0
log $ show f
-- This can be used to generate random numbers in
-- other ranges, for example 5.0 <= f' < 10.0.
f1 <- randomRange 5.0 10.0
f2 <- randomRange 5.0 10.0
log $ show f1 <> "," <> show f2
-- If you want a known seed, you can use the `purescript-random` library
-- which provides a `Gen` type for deterministic random number generation.
-- However, this is beyond the scope of this basic example.The PureScript code demonstrates how to generate random numbers using the Effect.Random module. Here’s a breakdown of the code:
We import necessary modules:
Effect.Consolefor logging,Effectfor the effect monad, andEffect.Randomfor random number generation.The
mainfunction is defined as anEffect Unit, which is similar toIO ()in Haskell.We use
randomIntto generate random integers between 0 and 99 (inclusive of 0, exclusive of 100).randomRangeis used to generate random floating-point numbers. By default, it generates numbers between 0.0 and 1.0.We demonstrate how to generate random numbers in a custom range (5.0 to 10.0) using
randomRange.The concept of seeded random number generation is mentioned, but not implemented in this basic example. PureScript has libraries like
purescript-randomthat provide more advanced functionality for deterministic random number generation.
To run this program, you would typically compile it with the PureScript compiler and then run it using Node.js:
$ pulp run
81,62
0.7242516798496246
7.123456,8.987654Note that the actual numbers generated will be different each time you run the program.
For more advanced random number generation techniques, including seeded generators, you might want to explore the purescript-random library or other similar libraries in the PureScript ecosystem.