F# 记录类型是作为结构体还是类实现的?
我在 F# 中使用记录类型来存储一些简单的数据,例如如下:
open Vector
type Point =
{
x: float;
y: float;
z: float;
}
static member (+) (p: Point, v: Vector) = { Point.x = p.x + v.x ; y = p.y + v.y ; z = p.z + v.z }
static member (-) (p: Point, v: Vector) = { Point.x = p.x - v.x ; y = p.y - v.y ; z = p.z - v.z }
static member (-) (p1: Point, p2: Point) = { Vector.x = p1.x - p2.x ; y = p1.y - p2.y ; z = p1.z - p2.z }
member p.ToVector = { Vector.x = p.x ; y = p.y ; z = p.z }
我无法确定这是否将实现为值类型或引用类型。
我尝试将 [
放在类型定义之前,但这会导致各种编译错误。
I'm using record types in F# to store some simple data, e.g. as follows:
open Vector
type Point =
{
x: float;
y: float;
z: float;
}
static member (+) (p: Point, v: Vector) = { Point.x = p.x + v.x ; y = p.y + v.y ; z = p.z + v.z }
static member (-) (p: Point, v: Vector) = { Point.x = p.x - v.x ; y = p.y - v.y ; z = p.z - v.z }
static member (-) (p1: Point, p2: Point) = { Vector.x = p1.x - p2.x ; y = p1.y - p2.y ; z = p1.z - p2.z }
member p.ToVector = { Vector.x = p.x ; y = p.y ; z = p.z }
I can't work out whether this will be implemented as a value or reference type.
I've tried putting [<Struct>]
before the type definition but this causes all sorts of compile errors.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
[]
是请求值类型的正确语法。它可以在“Expert F#”的第 6 章中看到,并且被 F# 2.0 接受:尽管如果将其写为
[] type Point =
(即全部在一行上) )它会产生许多警告(但没有错误)。您使用的是哪个版本的 F#?[<Struct>]
is the correct syntax for requesting a value type. It can be seen used in Chapter 6 of 'Expert F#', and this is accepted by F# 2.0:Though if you write it as
[<Struct>] type Point =
(ie all on one line) it produces a number of warnings (no errors, though). Which version of F# are you using?记录是类,但默认情况下所有字段都是不可变的。为了利用引用类型的“优势”,您必须将字段设置为可变(您可以将一些字段设置为不可变,一些设置为可变),然后修改它们的值:
Records are classes, but all fields are immutable by default. In order to use the "advantage" of reference types, you must set the fields as mutable (you can set some as immutable and some as mutable) and then modify their value:
根据这篇维基百科文章, http://en.wikipedia.org/wiki/F_Sharp_(programming_language ),记录类型被实现为具有定义的属性的类。
According to this wikipedia article, http://en.wikipedia.org/wiki/F_Sharp_(programming_language), record types are implemented as classes with properties defined.