gpt4 book ai didi

.net - 试图理解 F# 类定义语法

转载 作者:行者123 更新时间:2023-12-04 02:15:39 25 4
gpt4 key购买 nike

在学习了很多关于 F# 语言最重要特性的知识后,我现在正在接近 F# 类(class)。好吧,类定义语法并不容易理解,但我现在清楚了一些主要概念,但其他一些则不清楚。

1)我想知道的第一件事就是正确/不正确。我知道可以通过两种方式定义类:

  • 隐式类。这些类只有一个构造函数,在类的第一行中,有必要使用 let 绑定(bind)定义所有内部变量,为它们赋值。
  • 显式类。这些类有许多构造函数。它们通过 val 绑定(bind)接受未初始化的值。这些值必须在构造函数中全部初始化。如果构造函数为使用 val 绑定(bind)定义的至少一个私有(private)变量定义值失败,编译器会发疯。

  • 这是正确的吗???

    2) 我在理解显式类中构造函数的语法时遇到问题。
    考虑以下:

    这是第一个版本:
    (* COMPILES :) *)
    type MyType =
    val myval: int
    val myother: int
    (* Constructor *)
    new (a: int, b: int) = {
    myval = a;
    myother = b;
    }

    这是第二个版本:
    (* COMPILES :) *)
    type MyType =
    val myval: int
    val myother: int
    (* Constructor *)
    new (a: int, b: int) = {
    myval = a (* No semicolon *)
    myother = b (* No semicolon *)
    }

    这是最后一个版本:
    (* DOES NOT COMPILE :( *)
    type MyType =
    val myval: int
    val myother: int
    (* Constructor *)
    new (a: int, b: int) =
    myval = a (* Using the normal indent syntax, without {} *)
    myother = b (* Using the normal indent syntax, without {} *)

    我不明白为什么前两个版本可以编译,而使用常规缩进语法的第三个版本不能编译。
    这个问题只发生在构造函数中,因为在成员上我可以使用缩进语法
    (* COMPILES :) *)
    type MyType =
    val myval: int
    val myother: int
    (* Constructor *)
    new (a: int, b: int) = {
    myval = a (* No semicolon *)
    myother = b (* No semicolon *)
    }
    (* Indentation accepted, no {} to be inserted *)
    member self.mymember =
    let myvar = myval
    myvar + 10

    为什么新函数(构造函数)需要 {} 括号??????我不喜欢它,因为似乎考虑了一个序列。此外,当在 {} Racket 中,一条指令与另一条指令之间没有插入分号时,我的代码也会编译。为什么????

    最佳答案

    你写道(强调我的):

    Implicit classes. These classes have one constructor only, and in the first lines of the class, it is necessary to define, using the let binding, all internal variables assigning them a value.



    这实际上不是真的 - 您可以使用隐式语法来定义具有多个构造函数的类。事实上,我认为几乎总是使用隐式类语法是个好主意(因为它使声明更简单)。隐式类有一个主构造函数,这是您隐式获得的构造函数 - 此构造函数应采用最大数量的参数(但它可以是私有(private)的):
    type Foo(a:int, b:int) =
    do printfn "hello" // additional constructor code
    member x.Multiple = a * b // some members
    new(x:int) = Foo(x, x) // additional constructor

    要使构造函数私有(private),您可以编写
    type Foo private (a:int, b:int) =
    ...

    然后,您可以使用主构造函数作为初始化所有字段的好方法。

    关于.net - 试图理解 F# 类定义语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4972981/

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