gpt4 book ai didi

performance - 多态变体中的内联记录?

转载 作者:行者123 更新时间:2023-12-04 00:57:09 26 4
gpt4 key购买 nike

手册第 8 章“语言扩展”描述 "inline records" (8.17) :

The arguments of sum-type constructors can now be defined using the same syntax as records. Mutable and polymorphic fields are allowed. GADT syntax is supported. Attributes can be specified on individual fields. [...]



我正在寻找多态变体:
# type a = B of {x:int; mutable y:int} ;;
type a = B of { x : int; mutable y : int; }
# type b = `A of {u:int; mutable v:int} ;;
Line 1, characters 9-10:
Error: Syntax error

但这不起作用,所以现在我使用显式辅助记录类型代替......
据我现在理解,这既需要更多的内存,也有点慢。

我也可以通过多态变体获得这个很酷的功能吗?

最佳答案

在普通构造函数的情况下,编译器可以通过类型定义来区分:

type t = A of int * int | B
let f = function
| A (_,y) -> y
| B -> 0



type 'a t = A of 'a | B
let f = function
| A (_,y) -> y
| B -> 0

因此,可以优化第一个
A (_,y) -> y

进入“访问块的第二个字段”,同时仍然编译第二个案例
A (_,y) -> y

以“访问块的第一个字段中的元组,然后访问块的第二个字段”。

对于多态变体,不可能依靠不存在的类型定义来区分这两种解决方案。因此,它们的内存表示必须是统一的。这意味着多态变体总是采用一个参数,当只有一个参数时,标记构造函数的每个参数并不是很有用。

这就是内联记录不能与多态变体结合的原因。

关于performance - 多态变体中的内联记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61503391/

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