How can I select a random value from a list using F#

前端 未结 3 2062
独厮守ぢ
独厮守ぢ 2020-12-18 01:17

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.

I have a list like this:



        
3条回答
  •  隐瞒了意图╮
    2020-12-18 01:31

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

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

提交回复
热议问题