F# Types and Function signatures

Viewed 165

I'm new to F# and I'm trying a few thing to get my head around the language.

I have to two types almost identical (Coordinate and Vector). Because of this type inference cannot work properly and I have hard time to specify the correct type on each function.

It somehow undestand that's a Vector here:

type Coordinate = {X:int; Y:int}
type Vector = {X:int; Y:int}

let calculateVector (origin:Coordinate) (destination:Coordinate) = { X=destination.X-origin.X; Y= destination.Y-origin.Y;}

And here when I want a return type of Coordinate, I cannot find how to specify the return it for this function:

let calculateNextCoordinate (coordinate:Coordinate) direction = 
   match direction with
   | "N" -> { X=coordinate.X; Y=coordinate.Y-1 }
   | "NE" -> { X=coordinate.X+1; Y=coordinate.Y-1 }
   | "E" -> { X=coordinate.X+1; Y=coordinate.Y }
   | "SE" -> { X=coordinate.X+1; Y=coordinate.Y+1 }
   | "S" -> { X=coordinate.X; Y=coordinate.Y+1 }
   | "SW" -> { X=coordinate.X-1; Y=coordinate.Y+1 }
   | "W" -> { X=coordinate.X-1; Y=coordinate.Y }
   | "NW" -> { X=coordinate.X-1; Y=coordinate.Y-1 }
   | _ -> coordinate

I have this error on the default case: This expression was expected to have 'Vector' but here has type 'Coordinate'

i tired to have a look on this website for function signatures but could not something for my problem: https://fsharpforfunandprofit.com/posts/function-signatures/

Questions:

How do you fix this error?

Is it because inference type take by default the last type declared that match the properties (in my example Vector)?

Bonus: Is there a better way to handle this kind of situation in F#?

Thanks in advance

1 Answers
Related