简体   繁体   中英

F# Int * Int confusion

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. IE get my current X position or get my current Y position

2) Add to this variable so that I can move around the grid. IE 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!

In addition to what Ringil said, you can deconstruct a tuple using:

let xPos, yPos = gridPos

This is more terse/idiomatic in F#.

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#...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM