2

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

Jamie Dixon
  • 4,204
  • 4
  • 25
  • 47
  • And when I fully-qualify the Random parameter like so: System.Random().Next(0,9), I get a This is not a variable, constant, active recognizer or literal – Jamie Dixon Sep 19 '13 at 01:05
  • 1
    possible duplicate of [F# getting a list of random numbers](http://stackoverflow.com/questions/6062191/f-getting-a-list-of-random-numbers) – gradbot Sep 19 '13 at 01:20

1 Answers1

6

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.

John Palmer
  • 25,356
  • 3
  • 48
  • 67