'How to make a tuple give a random new tuple?

I am trying to take a position (a,b) and via the code receive a random new position (a,b).. I am having great trouble implementing the code and what I got is by far my best try..

type Teleport (a,b) = 
    inherit Item (a, b, ' ', Color.White, Color.White)
    override this.FullyOccupy() = true
    override this.InteractWith (p: Player) =
        let mutable posX = p.X
        let mutable posY = p.Y
        let rand = System.Random()
        posX <- rand.Next()
        posY <- rand.Next()

Can someone maybe explain why it is not working?

It is supposed to work as a teleporter in a game, where if the player moves to the first (a,b) should be transported to a new (random) (a,b) position. Thanks!



Solution 1:[1]

The reason your code doesn't work is that it never mutates the Player's position; InteractWith just copies the position into two local variables, and updates those.

This said, I strongly encourage you not to program in the OO-style if you want to learn F# - you'll be much happier going for a functional style.

One of the hallmarks of functional programming (FP) is immutability. For your teleport-thingy, this means NOT to mutate the Player's position, but to create a new player with the new position.

Try something along the following line

type Player = { X: int; Y: int; Name: string }

let teleport player =
    let rand = System.Random()
    { player with X = rand.Next 100
                  Y = rand.Next 100 }

Also, try not to reach for a class as the solution for every problem, reach for a function instead; in the above, teleport is just a function Player -> Player.

I truly hope you'll enjoy F#; it's a great language for doing FP on .NET.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Peter O.