Functional Programming - Avoid making my variable mutable when counting it down

Viewed 85

Yesterday's thread

First let me thank you for yesterday's replies. I was able to continue.

My current issue is that I have been able to avoid making all variables mutable except for currentHP of a Pokemon. Code of my battle first, explanation follows.

let angriffFighter(fighterPair:list<Domain.Pokemon>) =
    let dmg = hit fighterPair.[0] fighterPair.[1]
    fighterPair.[1].currentHP <- fighterPair.[1].currentHP-dmg

The function "hit" calculates dmg dealt and returns an int. currentHP is the only remaining variable I can't seem to make immutable. I need to reduce it in every battleround and I want it to reset to maxHP after the fight.

How would I tackle this issue?

1 Answers

Use a copy-and-update expression to return a new record value with the changed fields:

let angriffFighter (fighterPair : list<Domain.Pokemon>) =
    let dmg = hit fighterPair.[0] fighterPair.[1]
    let new1 = { fighterPair.[1] with currentHP = fighterPair.[1].currentHP - dmg }
    [ fighterPair.[0]; new1 ]

But really, instead of passing a list around as a pair, it'd be much easier to just use a pair (a tuple):

let angriffFighter (x, y) =
    let dmg = hit x y
    x, { y with currentHP = y.currentHP - dmg }

This version takes a tuple as input and also returns a tuple of the same type. Simpler and safer, because with a tuple, you know that the first and the second element will be there. This is in contrast to a list, where indexing into a list (using .[0], .[1], etc.) is unsafe, because you don't know whether or not there's going to be an element at that index.

Related