Reputation: 121
I have two sequences, one called Hand with 5 elements another called Deck of some n size. I need to first append the 1st element of Deck to Hand(creates new Seq of size 6) then run a function on that new Sequence to get a score, say for example 50. Then I need to append the 2nd element of Deck to Hand (again new Seq of Size 6) and runs the function to get say score 25.
This needs to be done for all elements in Deck so that I have a bunch of scores. It doesn't matter whether these scores are saved into a list or however else possible. Then I need to find the average of all these results and return that value.
Here is a pseudo code example of what I am after-
Hand = {S2; C5; HK; D9; C1}, Deck = {...a bunch of cards...}
score[0] = CalcScore (Hand.append Deck[0]) //e.g. CalcScore ({S2; C5; HK; D9; C1; HJ})
score[1] = CalcScore (Hand.append Deck[1]) //e.g. CalcScore ({S2; C5; HK; D9; C1; D2})
score[n] = CalcScore (Hand.append Deck[n]) //e.g. CalcScore ({S2; C5; HK; D9; C1; SQ})
return averageScore = score.average
I know that if I can create either a list or sequence that contains each of the separate scores I can just use Seq.average/List.average but I am unsure of how to do the 1st part with appending and running a function for each element separately and saving that value.
I have a hard time understanding how to create Higher Order functions and F# is new to me and quite different from the few languages I have some knowledge in.
Any guidance or information will help greatly, thanks!
Upvotes: 2
Views: 445
Reputation: 80744
First, write a function to calculate the score given a card to append:
let scoreWithAppendedCard card =
CalcScore (Seq.append Hand [card])
Awesome! Now do that for every card in the deck:
let allScores = Deck |> Seq.map scoreWithAppendedCard
Now all that's left is compute the average:
let averageScore = Seq.average allScores
Or you could do all that in one go, without naming intermediate values:
let averageScore =
Deck
|> Seq.map (fun card -> CalcScore (Seq.append Hand [card]))
|> Seq.average
Upvotes: 3