How to set default argument value in F#? -


take function example:

// sequence of random numbers open system  let randomsequence m n=      seq {          let rng = new random()         while true             yield rng.next(m,n)     }   randomsequence 8 39 

the randomsequence function takes 2 arguments: m, n. works fine normal function. set default m, n, example:

(m = 1, n = 100) 

when there's no arguments given, function take default value. possible in f#?

you can achieve same effect overloading discriminated union.

here's suggestion based on op:

type range = default | between of int * int  let randomsequence range =      let m, n =         match range         | default -> 1, 100         | between (min, max) -> min, max      seq {         let rng = new random()         while true             yield rng.next(m, n) } 

notice introduction of range discriminated union.

here (fsi) examples of usage:

> randomsequence (between(8, 39)) |> seq.take 10 |> seq.tolist;; val : int list = [11; 20; 36; 30; 35; 16; 38; 17; 9; 29]  > randomsequence default |> seq.take 10 |> seq.tolist;; val : int list = [98; 31; 29; 73; 3; 75; 17; 99; 36; 25] 

another option change randomsequence ever take tuple instead of 2 values:

let randomsequence (m, n) =      seq {         let rng = new random()         while true             yield rng.next(m, n) } 

this allow define default value, this:

let defaultrange = 1, 100 

here (fsi) examples of usage:

> randomsequence (8, 39) |> seq.take 10 |> seq.tolist;; val : int list = [30; 37; 12; 32; 12; 33; 9; 23; 31; 32]  > randomsequence defaultrange |> seq.take 10 |> seq.tolist;; val : int list = [72; 2; 55; 88; 21; 96; 57; 46; 56; 7] 

Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -