简体   繁体   中英

F# List.Map using a random number

I want to create a list of 20 random numbers. I wrote this:

let numberList = [ 1 .. 20 ] 
let randoms = 
    numberList 
    |> List.map (fun (x) -> System.Random().Next(0,9)) 

And I got this:

val numberList : int list =
  [1; 2; 3; 4; 5; 6; 7; 8; 9; 10; 11; 12; 13; 14; 15; 16; 17; 18; 19; 20]
val randoms : int list =
  [7; 7; 7; 7; 7; 7; 7; 7; 7; 7; 7; 7; 7; 7; 7; 7; 7; 7; 7; 7]

Which makes sense. The problem is that I want to pass in a random number each time the function is evaluated like this:

let numberList = [ 1 .. 20 ] 
let randoms = 
    numberList 
    |> List.map (fun (Random().Next(0,9)) -> x) 

but I am getting a "The pattern discriminator 'Random' is not defined" exception.

Am i approaching this problem the wrong way? Thanks in advance

In your original version, you create a new Random object at each iteration. As this is seeded with the current time, you always create the same sequence.

You need to create the object outside map like so

let RNG = new System.Random()
numberlist |> List.map (fun x -> RNG.Next(0,9))

Although a more elegant solution would be

let RNG = new System.Random()
let randoms = List.init 20 (fun _ -> RNG.Next(0,9))

Your second version fails because you are trying to treat Random as a pattern which makes no sense in this situation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM