1

我写了以下

[<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}

现在我正在尝试以这种方式使用它:

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

它给了我一个编译器错误,但我很确定度量单位的表达是正确的。我的错误是什么?

4

2 回答 2

3

您尝试用于指定返回类型的语法不正确。它应该如下所示:

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

要指定函数返回 type 的值Vector3<m>,需要在结果中添加类型注解,这是通过编写 来完成的let foo <arguments> : T = <expr>。给参数添加类型注解时,需要用括号括起来(这样语法就没有歧义了)。正如 Paolo 在评论中指出的那样,您的使用是->在说这dt是一个函数,因为注释float<s> -> Vector3<m>已附加到 parameter dt

为了使代码编译,我还必须在你的 中添加一个(+)操作符的实现Vector3,但我假设你已经有了它(并且在发布问题时将它遗漏了)。

于 2011-11-29T11:44:31.033 回答
1

我以这种方式解决了(但我不确定原因)。

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

如果我明确定义返回类型,编译器似乎会失败。如果我删除它似乎无论如何都能推断出正确的类型。但这是为什么呢?

除此之外,在某些情况下,类型声明中的名称冲突迫使我明确指定返回类型。所以我认为这最终不是正确的解决方案。

于 2011-11-29T11:27:31.763 回答