f# - Immutable game objects -
i'm trying wrap head around f#, , part it's making sense, people keep saying every problem can solved immutable constructs. objects in game? have changing variables (x, y, xspeed, yspeed, score, health etc...)
lets have player object, defined in c# as:
public class player extends gameobject { private int score = 0; private int x = 0; private int y = 0; ... more variables public player() { } public void addscore(int amount) { score += amount; } public void addx(int amount) { x += amount; } public void addy(int amount) { y += amount; } ... more methods }
this code has variables inherently there being that: "variables." how code translate immutable code?
by definition immutable can't change, in order update immutable game object new object contains updates must created.
type player(score, x, y) = member this.addscore(amount) = player(score + amount, x, y) member this.addx(amount) = player(score, x + amount, y) member this.addy(amount) = player(score, x, y + amount) let first = player(0, 0, 0) let firstmoved = first.addx(2)
passing every variable constructor can unwieldy , slow. avoid organize data different classes. allow reuse of smaller objects create bigger ones. since these objects immutable, contain same data , can reused freely without worry.
type stats(score, lives) = member this.addpoints(points) = stats(score + points, lives) type location(x, y) = member this.move(x2, y2) = location(x + x2, y + y2) type player(stats : stats, location : location) = member this.addscore(amount) = player(stats.addpoints(amount), location) member this.addx(amount) = player(stats, location.move(amount, 0)) let first = player(stats(0, 1), location(0, 0)) let firstmoved = first.addx(2)
f# supports mutable data. can write original class this.
type player() = inherit gameobject() let mutable score = 0 let mutable x = 0 let mutable y = 0 member this.addscore(amount) = score <- score + amount member this.addx(amount) = x <- x + amount member this.addy(amount) = y <- y + amount
Comments
Post a Comment