Question

I've written the following

[<Measure>]
type m

[<Measure>]
type s

[<Measure>]
type v = m/s

type Vector3<[<Measure>] 'a> =
    {
    X : float<'a>
    Y : float<'a>
    Z : float<'a>
    }
    static member (*)
        (v:Vector3<'a>,f:float<'b>):Vector3<'a*'b> =
        { X = v.X*f; Y = v.Y*f ; Z = v.Z * f}

Now I'm trying to use it this way:

let next_pos (position:Vector3<m> , velocity: Vector3<m/s> ,dt : float<s>  ->  Vector3<m>) =
     position + (velocity * dt)

It gives me a compiler error, but I'm pretty sure the measure unit are expressed right. What's my mistake?

Was it helpful?

Solution

The syntax you tried to use for specifying the return type was incorrect. It should look like this:

let next_pos (position:Vector3<m>, velocity:Vector3<m/s>, dt:float<s>) : Vector3<m> = 
  position + (velocity * dt) 

To specify that the function returns a value of type Vector3<m>, you need to add type annotation to the result, which is done by writing let foo <arguments> : T = <expr>. When adding type annotations to parameters, these need to be parenthesized (so the syntax is not ambiguous). As noted by Paolo in a comment, your use of -> was saying that dt is a function, because the annotation float<s> -> Vector3<m> was attached to the parameter dt.

To make the code compile, I also had to add an implementation of (+) operator to your Vector3, but I assume you have that already (and just left it out when posting the question).

OTHER TIPS

I solved this way (but I'm not sure about the reason).

let next_pos (position:Vector3<m> , velocity: Vector3<m/s> ,dt : float<s> ) =
     position + (velocity * dt)

It seems that the compiler fails if I explicetly define the return type. If I remove it seems able to infer the correct type anyway. But why this?

In addition to that, there are situations in which name clashes in type declaration force me to explictely specify the return type. So I don't think this is the right solution in the end.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top