functional programming - How to generate data idiomatically in f# inline in code -


lets attempting implement sort of poker program in f#. firstly correct use of type system, massive newbie here.

type suit =     | hearts     | diamonds     | spades     | clubs  type card = {     suit:suit     rank:int }  type hand = {     cards:list<card> } 

anyway suppose want function return me randomised list of possible holding cards. guess there 2 functions chain together, having hard time implementing them without creating loads of objects. each of functions in list module return new list , let keyword makes impossible change value of reference. functional way of achieving then. far have this

let generatecards = {     let ranks = [ 1..52 ]...  }   let shuffle cards = {  }  let cards = shuffle generatecards 

one way shuffle deck zip sequence of random numbers, sort numbers, unzip again.

let allcards =    [ rank in 2..14       suit in [hearts; diamonds; spades; clubs]         yield { suit = suit; rank = rank } ]  let shuffle cards =      let rnd = system.random()     let rndsequence = seq.initinfinite (fun _ -> rnd.next())     seq.zip cards rndsequence |> seq.sortby snd |> seq.map fst |> seq.tolist  shuffle allcards 

the above simplified (nod @daveshaw's comment), though @ cost of making less obvious human, sorting sequence randomly generated key:

let shuffle cards =      let rnd = system.random()     cards |> list.sortby (fun _ -> rnd.next()) 

or simpler (though, possibly, more performance impact):

let shuffle cards = list.sortby (fun _ -> system.guid.newguid()) cards 

and ultimate simplicity, go point-free style:

let shuffle = list.sortby (fun _ -> system.guid.newguid()) 

Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -