如何使用F#从列表中选择一个随机值 [英] How can I select a random value from a list using 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)]
推荐答案
您的问题是您混用了Array
s和F#List
s(*type*[]
是Array
的类型符号).您可以像这样修改它以使用列表:
Your problem is that you are mixing Array
s and F# List
s (*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#从列表中选择一个随机值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!