本文介绍了如何使用 F# 从列表中选择一个随机值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 F# 的新手,我想弄清楚如何从字符串列表/数组中返回随机字符串值.

I'm new to F# and I'm trying to figure out how to return a random string value from a list/array of strings.

我有一个这样的列表:

["win8FF40", "win10Chrome45", "win7IE11"]

如何从上面的列表中随机选择并返回一项?

How can I randomly select and return one item from the list above?

这是我的第一次尝试:

let combos = ["win8FF40";"win10Chrome45";"win7IE11"]

let getrandomitem () =
  let rnd = System.Random()
  fun (combos : string[]) -> combos.[rnd.Next(combos.Length)]

推荐答案

你的问题是你正在混合 Arrays 和 F# Lists (*type*[]Array 的类型符号).您可以像这样修改它以使用列表:

Your problem is that you are mixing Arrays and F# Lists (*type*[] is a type notation for Array). You could modify it like this to use lists:

let getrandomitem () =
  let rnd = System.Random()
  fun (combos : string list) -> List.nth combos (rnd.Next(combos.Length))

话虽如此,索引到 List 通常是一个坏主意,因为它具有 O(n) 性能,因为 F# 列表基本上是一个链接列表.如果可能的话,你最好将 combos 变成一个数组:

That being said, indexing into a List is usually a bad idea since it has O(n) performance since an F# list is basically a linked-list. You would be better off making combos into an array if possible like this:

let combos = [|"win8FF40";"win10Chrome45";"win7IE11"|]

这篇关于如何使用 F# 从列表中选择一个随机值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-28 16:56
查看更多