WilliamG
WilliamG

Reputation: 137

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!

Upvotes: 2

Views: 120

Answers (1)

Koenig Lear
Koenig Lear

Reputation: 2436

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(); }

Upvotes: 4

Related Questions