gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 23:52:10 25 4
gpt4 key购买 nike

以这个函数为例:

// 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
randomSequence函数有两个参数: m, n .这作为正常功能工作正常。我想为 m, n 设置默认值, 例如:
(m = 1, n = 100)

当没有给出参数时,函数采用默认值。在 F# 中可能吗?

最佳答案

您可以经常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]

关于f# - 如何在 F# 中设置默认参数值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30255271/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com