I'm trying to figure out how to write strategy games using Scala functionally, but unfortunately I seem to be stuck at the very basics. (This is not homework, but my attempts to learn something new, namely "pure" functional programming.)
Take the following simple βgameβ: the player (the only one) has x identical pieces on an infinite row of squares. Pieces start at square 0, and each move he can move one piece forward one square.
I will use as a data structure List[Int], each element is the position (square) of one part.
To generate the possible steps, I came up with:
def moves(start: List[Int]) =
(0 until start.length).map({i => start.updated(i, start(i) + 1)});
val m1 = moves(List(0,0,0))
val m2 = moves(List(1,2,3))
What I don't like is the use of the index loop (0 until start.length). This does not seem to me "functional." Is this the right way to do this, or is there a better way?
Now, in my example game, all the parts are identical, so in the case of m1all three possible movements are also identical and can / should be combined in one move. I changed movesto sort each move item so that I can get a list of individual items:
def moves(start: List[Int]) =
(0 until start.length).map({i => start.updated(i, start(i) + 1).sorted}).distinct;
val m1 = moves(List(0,0,0))
val m2 = moves(List(1,2,3))
However, this requires that the data structure be sortable, and in my "real" application it most likely is not List[Int], but a Tuple or case class. I think I need a method distinctthat takes a function that defines equality. How to implement this?