gpt4 book ai didi

F#:如何打印自定义类?

转载 作者:行者123 更新时间:2023-12-05 00:59:11 24 4
gpt4 key购买 nike

我正在尝试自学 F#。我已经设置了一个简单的类,并希望能够打印它。

是否有与 C++ 的重载 operator<<(std::ostream&,const MyClass&) 等价的惯用语?这将允许我打印,例如,printfn ?如果不是,自定义类的“标准”方式是什么?

为了具体起见,这里是当前的类

type Vect(x: float, y: float) = 
new() = Vect(0.,0.)
member this.x = x
member this.y = y
static member (-) (v1: Vect, v2: Vect) =
Vect(v1.x-v2.x,v1.y-v2.y)
member this.Magnitude() =
sqrt(x**2. + y**2.)

最佳答案

StructuredFormatDisplay 也可以使用属性。

[<StructuredFormatDisplay("Name: {FullName}")>]
type Person(first, last) =
member val First = first
member val Last = last
member this.FullName = first + " " + last
override this.ToString() = last + ", " + first

let person = Person("John", "Doe")
printfn "%O" person
> Doe, John
printfn "%A" person
> Name: John Doe

关于F#:如何打印自定义类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17547127/

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