gpt4 book ai didi

struct - 如何在 F# 中为结构体定义一个 ctor,进而调用该结构体的默认 ctor

转载 作者:行者123 更新时间:2023-12-02 15:23:59 26 4
gpt4 key购买 nike

我们如何在 F# 中为不可变结构定义一个仅接受部分字段的构造函数。或者,与 C# 相比,我们如何在 f# 中将结构清零(例如在下面的 c# 示例中调用 this())?

c#

struct Point
{
private readonly int _x;
private readonly int _y;
public Point(int x) : this() // Will zero the struct
{
_x = x;
}
public Point(int y) : this() // Will zero the struct
{
_y = y;
}

}

上面的 Point(x) 向量通过调用 this() 将结构清零,然后设置单个字段。这就是我所追求的。下面的例子被大大简化了,问题是如何将结构体清零,然后只设置一个字段。

f#

type Point =
struct
val X: float
val Y: float

new(x: float) = ? // how to zero out the struct and then set ONLY X ?

end

最佳答案

您可以使用Point(x, 0.0)调用结构中的另一个构造函数:

type Point =
struct
val X: float
val Y: float
new(x: float, y: float) = { X = x; Y = y }
new(x: float) = Point(x, 0.0)
end

顺便说一句,您还可以使用带有 Struct 属性的普通 type 定义来声明结构。这当然是一个风格问题,但我更喜欢这种变体:

[<Struct>]
type Point =
val X: float
val Y: float
new(x: float, y: float) = { X = x; Y = y }
new(x: float) = Point(x, 1.0)

关于struct - 如何在 F# 中为结构体定义一个 ctor,进而调用该结构体的默认 ctor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25995332/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com