Skip to content

Instantly share code, notes, and snippets.

@deneuxj
Created January 4, 2013 10:04
Show Gist options
  • Save deneuxj/4451408 to your computer and use it in GitHub Desktop.
Save deneuxj/4451408 to your computer and use it in GitHub Desktop.
Demonstration of how to extend System.Random using extension methods in F#.
open System
(* Low-level F# implementation *)
let newRandomChar getRandomInt (chars : char[]) =
let idx = getRandomInt()
chars.[idx]
let newRandomWord (getRandomChar : unit -> char) length =
let chars =
Array.init length (fun _ -> getRandomChar())
String(chars)
(* Extension methods for System.Random *)
type System.Random
with
member this.NextChar(chars : char[]) =
let getRandomInt() = this.Next(chars.Length)
newRandomChar getRandomInt chars
member this.NextWord(length, chars) =
let getRandomChar() = this.NextChar(chars)
newRandomWord getRandomChar length
(* Testing *)
let chars =
[| [| 'a' .. 'z' |]
[| 'A' .. 'Z' |]
[| '0' .. '9' |]
|]
|> Array.concat
let rnd = new System.Random()
for i in 1..10 do
printfn "%i: %s" i (rnd.NextWord(8, chars))
@johnbfair
Copy link

Very helpful Johann! Now I get what you meant. I have written C# extension methods, but this is the first time seeing an F# version. Cool! :)

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