我写了以下内容

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

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

有帮助吗?

解决方案

您尝试使用用于指定返回类型的语法不正确。看起来应该这样:

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

要指定该函数返回类型的值 Vector3<m>, ,您需要在结果中添加类型注释,这是通过写作来完成的 let foo <arguments> : T = <expr>. 。将类型注释添加到参数时,需要将这些注释添加到括号(因此语法不是模棱两可的)。正如保罗在评论中指出的那样,您的使用 -> 就是这样说的 dt 是一个功能,因为注释 float<s> -> Vector3<m> 附在参数上 dt.

为了使代码编译,我还必须添加 (+) 操作员 Vector3, ,但我认为您已经有(在发布问题时都遗漏了它)。

其他提示

我这样解决了(但我不确定原因)。

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

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

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top