在 F# 中将向量与测量单位相乘
我已经编写了以下内容
[<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)
它给了我一个编译器错误,但我很确定度量单位的表达是正确的。 我有什么错?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您尝试用于指定返回类型的语法不正确。它应该如下所示:
要指定函数返回
Vector3
类型的值,您需要向结果添加类型注释,这是通过编写let foo来完成的。论据> : T = <表达式>
。当向参数添加类型注释时,需要将它们放在括号中(这样语法才不会产生歧义)。正如 Paolo 在评论中指出的那样,您使用->
是说dt
是一个函数,因为注释float
-> Vector3附加到参数dt
。为了使代码编译,我还必须将
(+)
运算符的实现添加到您的Vector3
中,但我假设您已经有了(并且在发布问题)。The syntax you tried to use for specifying the return type was incorrect. It should look like this:
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 writinglet 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 thatdt
is a function, because the annotationfloat<s> -> Vector3<m>
was attached to the parameterdt
.To make the code compile, I also had to add an implementation of
(+)
operator to yourVector3
, but I assume you have that already (and just left it out when posting the question).我是这样解决的(但我不确定原因)。
如果我显式定义返回类型,编译器似乎会失败。如果我删除它似乎无论如何都能推断出正确的类型。
但为什么会这样呢?
除此之外,在某些情况下,类型声明中的名称冲突迫使我明确指定返回类型。所以我认为这最终不是正确的解决方案。
I solved this way (but I'm not sure about the reason).
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.