Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

207
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda