Created
January 4, 2013 10:04
-
-
Save deneuxj/4451408 to your computer and use it in GitHub Desktop.
Demonstration of how to extend System.Random using extension methods in F#.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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! :)