Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

206
Views
F# System.Random duplicate values

I'm trying to use System.Random in F# but keep getting duplicate values. I'm aware that if I create a new instance of System.Random each time I do .Next i might get duplicate values. What I'm trying to achive is setting a random id on each record when creating them. Here is an example of the problem in code:

[<AutoOpen>]
module Domain = 
    type Test = {id: int; ....} 

module Test =

    let r = System.Random() 

    let t create =
        {id = r.Next(); ....}


let a = Test.create
let b = Test.create

In the code above bot a and b gets the same id.

What I'm guessing is happening is that let r = System.Random() doesn't get treated as a variable but as a function which returns a new instance of Random. Is this correct? And how can I Solve this problem?

Thanks!

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You need to pass a unit () in your create function otherwise is a value (that's only calculated the first time).

open System


module T =
    type Test = {id: int; } 

    let r = System.Random() 

    let create () =
        {id = r.Next(); }
 

[<EntryPoint>]
let main _ =

    let a = T.create ()
    let b = T.create ()
    printfn "a = %A" a
    printfn "b = %A" b

This yields different values.

a = { id = 1528807395 }   
b = { id = 1526175776 }

This solves your immediate problem. However, it's common practice to create stateless functions. Your Random variable contains state thus it must be passed as parameter.

    let create (r:Random) =
        {id = r.Next(); }
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!