Reputation: 53
I am trying to make a collision method in a class in f#. The collision method should have one input which is time. The method should check a number of drones that should be moving with time and whether some of them will collide. A collision is defined as being within 5 "blocks" of each other.
I have so far this code for the method.
type Airspace(drones:Drone list) =
let mutable drones = drones
member x.Drones with get() = drones
member x.Collision(time:int) =
for d = 1 to time do
for i = 1 to drones.Length do
for j = 1 to drones.Length do
if drones.Item(i).Position.Item1 - drones.Item(j).Position.Item1 >= -5.0 || drones.Item(i).Position.Item1 - drones.Item(j).Position.Item1 <= 5.0
then if drones.Item(i).isFinished() = True && drones.Item(j).isFinished() = True then printfn "Drone: %A will collide with %A" (drones.Item(i)) (drones.Item(j))
By the way drones is a list of Drones and a drone has a current position as a tuple floatfloat, a destination also as a floatfloat and speed which is a float.
I am pretty sure this is wrong
drones.Item(i).Position.Item1
But I am not sure how I can access the first i'th element in a list and then take only the first element of the tuple and compare it with another one. How can I do this?
Upvotes: 0
Views: 377
Reputation: 26194
Well, it's not 100% wrong, it might work but yes, the recommendation is not to use ItemX
and instead to pattern match the tuple elements, so you can do this:
let (xi, _) = drones.Item(i).Position
let (xj, _) = drones.Item(j).Position
if xi - xj >= -5.0 || xi - xj <= 5.0
Btw, if you don't really need to use the index you can also change the loops to:
for di in drones do
for dj in drones do
let (xi, _) = di.Position
let (xj, _) = dj.Position
Also note that you can use the function List.allPairs
piped to List.tryFind
instead of for loops.
Upvotes: 1