Take this function as an example:
// Sequence of random numbers
open System
let randomSequence m n =
seq {
let rng = Random ()
while true do
yield rng.Next (m, n)
}
randomSequence 8 39
The randomSequence
function takes two arguments: m, n
. This works fine as a normal function. I would like to set the default for m, n
, for example:
(m = 1, n = 100)
When there's no arguments given, the function take the default value. Is it possible in F#?
You can often achieve the same effect as overloading with a Discriminated Union.
Here's a suggestion based on the OP:
type Range = Default | Between of int * int
let randomSequence range =
let m, n =
match range with
| Default -> 1, 100
| Between (min, max) -> min, max
seq {
let rng = new Random()
while true do
yield rng.Next(m, n) }
Notice the introduction of the Range
Discriminated Union.
Here are some (FSI) examples of usage:
> randomSequence (Between(8, 39)) |> Seq.take 10 |> Seq.toList;;
val it : int list = [11; 20; 36; 30; 35; 16; 38; 17; 9; 29]
> randomSequence Default |> Seq.take 10 |> Seq.toList;;
val it : int list = [98; 31; 29; 73; 3; 75; 17; 99; 36; 25]
Another option is to change the randomSequence ever so slightly to take a tuple instead of two values:
let randomSequence (m, n) =
seq {
let rng = new Random()
while true do
yield rng.Next(m, n) }
This would allow you to also define a default value, like this:
let DefaultRange = 1, 100
Here are some (FSI) examples of usage:
> randomSequence (8, 39) |> Seq.take 10 |> Seq.toList;;
val it : int list = [30; 37; 12; 32; 12; 33; 9; 23; 31; 32]
> randomSequence DefaultRange |> Seq.take 10 |> Seq.toList;;
val it : int list = [72; 2; 55; 88; 21; 96; 57; 46; 56; 7]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With