Rashid Noor
Rashid Noor

Reputation: 23

How to do sum and assign value in F#?

What is wrong with code when I run this code it doesn't run if statement and there is warning on assigning value to player variable. I'm new at F# so please guide me on how I can sum random number and player value and assign it to player and then if statement works.

...let player=0
   let dealer=0
   for i = 1 to 10 do
   let randnum=randomCh()
   let randnum2=randomCh()
   player=randnum+player
   dealer=randnum2+dealer
   Console.Write("Player revealed cards.\n")
   playercards()
   Console.Write("Dealer revealed cards.\n")
   playercards()
   if player>=21 || dealer>=21 then result()...

Upvotes: 0

Views: 107

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236208

Values are immutable in F#. If you want to declare mutable variable, use mutable keyword

let mutable player = 0
let mutable dealer = 0

To assign new value to mutable variable you should use <- operator (= is a comparison)

for i = 1 to 10 do
    player <- player + randomCh()
    dealer <- dealer + randomCh()

Further reading Values in F#

In F# you can use printf instead of Console.Write. Consider also using immutable values with recursion instead of loop with mutable variables. I don't know rules of blackjack or whatever game you are creating, but here is an example of recursive approach:

type GameResult = Player | Dealer | Draw

let rec notblackjack player dealer round =
    if player >= 21 then Dealer
    elif dealer >= 21 then Player
    elif round = 10 then Draw // in this game we have draw on round 10
    else blackjack (player + randomCh()) (dealer + randomCh()) (round + 1)

notblackjack 0 0 1 |> printfn "%A"

Upvotes: 2

Related Questions