Skip to content

Instantly share code, notes, and snippets.

@tugberkugurlu
Created November 6, 2016 00:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tugberkugurlu/1b227e0500f352ac2183256f489c485e to your computer and use it in GitHub Desktop.
Save tugberkugurlu/1b227e0500f352ac2183256f489c485e to your computer and use it in GitHub Desktop.
let randomString len =
let chars = "ABCDEFGHIJKLMNOPQRSTUVWUXYZ0123456789"
let charsLength = chars.Length
let random = System.Random()
let randomChars = [|for i in 0..len -> chars.[random.Next(charsLength)]|]
new System.String(randomChars)
let randomString =
let chars = "ABCDEFGHIJKLMNOPQRSTUVWUXYZ0123456789"
let charsLength = chars.Length
let random = System.Random()
fun len ->
let randomChars = [|for i in 0..len -> chars.[random.Next(charsLength)]|]
new System.String(randomChars)
@tugberkugurlu
Copy link
Author

@mathias-brandewinder
Copy link

mathias-brandewinder commented Nov 6, 2016

Perhaps this clarifies - this is equivalent to utils2:

let randomString = 

    let chars = "ABCDEFGHIJKLMNOPQRSTUVWUXYZ0123456789"
    let charsLength = chars.Length
    let random = System.Random()

    // create the function
    let generateString len =
        let randomChars = [|for i in 0..len -> chars.[random.Next(charsLength)]|]
        new System.String(randomChars)
    
    // now return the function
    generateString 

@mathias-brandewinder
Copy link

mathias-brandewinder commented Nov 6, 2016

I didn't know String could take an array of char in the constructor, that's a convenient trick :)
Instead of

    // omitted
    let randomChars = [| for i in 0..len -> chars.[random.Next(charsLength)] |]
    new System.String(randomChars)

... you could then go all out and do:

    [| for i in 0..len -> chars.[random.Next(charsLength)] |]
    |> System.String

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment