Reputation: 343
Firsly, I'd just like to state, I am completely new to this language and as of right now it seems extremely strange to me (As a Java/C# user).
I'm currently doing a uni project whereby I have to navigate a grid using pathfinding (Not even close to this point, will deal with it later down the line), I have created a 2d array with a size of 10x10 however I've found that I can store my current position by using something like let mutable position = 0,0 which gives me a type of int * int.
This seems great to me as I can store my X and Y location easily, however I've run into a couple of issues with this
1) Get the individual values in the variable. I.E get my current X position or get my current Y position
2) Add to this variable so that I can move around the grid. I.E position <- position + (5, 5)
Again, I've only had a small amount of experience with this language so please be gentle though I seem to grasp the basics quite well.
Thanks for any help provided!
Upvotes: 2
Views: 943
Reputation: 6537
You can get the individual values in a variable by using the fst
or snd
functions like so (note that this only works when you have size 2 tuples):
let gridPos = 1, 2
//val gridPos : int * int = (1, 2)
let xPos = fst gridPos
//val xPos : int = 1
let yPos = snd gridPos
//val yPos : int = 2
As for the 2nd question, you can overwrite the addition operator to allow for tuple of int*int
addition like so:
let (+) a b = (fst a + fst b, snd a + snd b)
//val ( + ) : int * int -> int * int -> int * int
let newValue = gridPos + (2,5)
//val newValue : int * int = (3, 7)
That said you should generally avoid mutable state in F#...
Upvotes: 4
Reputation: 12174
In addition to what Ringil said, you can deconstruct a tuple using:
let xPos, yPos = gridPos
This is more terse/idiomatic in F#.
Upvotes: 9