如何在F#中设置默认参数值?

时间:2015-05-15 08:50:01

标签: f#

以此功能为例:

// Sequence of random numbers
open System

let randomSequence m n= 
    seq { 
        let rng = new Random()
        while true do
            yield rng.Next(m,n)
    }


randomSequence 8 39

randomSequence函数有两个参数:m, n。这作为正常功能正常工作。我想设置m, n的默认值,例如:

(m = 1, n = 100)

如果没有给出参数,则该函数采用默认值。在F#中可以吗?

4 个答案:

答案 0 :(得分:13)

您经常可以achieve the same effect as overloading with a Discriminated Union

以下是基于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) }

请注意引入Range被歧视的联盟。

以下是一些(FSI)使用示例:

> 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]

另一种选择是稍微改变randomSequence以取一个元组而不是两个值:

let randomSequence (m, n) = 
    seq {
        let rng = new Random()
        while true do
            yield rng.Next(m, n) }

这将允许您定义默认的,如下所示:

let DefaultRange = 1, 100

以下是一些(FSI)使用示例:

> 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]

答案 1 :(得分:9)

  

仅允许在成员[...]

上使用可选参数

SQL Fiddle

所以,对于你目前的例子,我认为这是不可能的。 但你可以包装功能:

type Random =
    static member sequence(?m, ?n) =
        let n = defaultArg n 100
        let rng = new System.Random()
        match m with
        | None -> Seq.initInfinite (fun _ -> rng.Next(1, n))
        | Some(m) -> Seq.initInfinite (fun _ -> rng.Next(m, n))

然后像这样使用它:

let randomSequence = Random.sequence(2, 3)
let randomSequence' = Random.sequence(n = 200)
let randomSequence'' = Random.sequence()

说明:可选参数可以完全选项 al( m )或 defaultArg s( n ) 。我喜欢阴影(重用相同名称)这些参数,但这是值得商榷的。

答案 2 :(得分:3)

let randomSequence m n= 
    seq { 
    let rng = new Random()
    while true do
        yield rng.Next(m,n)
    }

let randomSequenceWithDefaults() =
    randomSequence 1 100

相反,请致电randomSequenceWithDefaults()

答案 3 :(得分:3)

这似乎是解决这个问题最优雅的方法:

//define this helper function
let (|Default|) defaultValue input =
    defaultArg input defaultValue

//then specify default parameters like this
let compile (Default true optimize) = 
    optimize

//or as the OP asks
let randomSequence (Default 1 m) (Default 100 n)
  seq { 
      let rng = new Random()
      while true do
          yield rng.Next(m,n)
  }

现金: http://fssnip.net/5z