gpt4 book ai didi

haskell - 为什么要对该记录进行类型检查?

转载 作者:行者123 更新时间:2023-12-02 16:43:55 24 4
gpt4 key购买 nike

给定数据类型

data Foo = Foo { one :: Int, two :: String } deriving (Show)

不完整的表达式通过类型检查——例如

foo :: Foo
foo = Foo { one = 5 }

main = print foo

类型检查(发出有关不完整记录的警告),然后(显然)在遇到表达式时崩溃。为什么会通过?如果没有记录语法,则不会(即 bar = Foo 5::Foo)。

最佳答案

Haskell 2010 报告在 3.15.2 Construction Using Field Labels 部分中提到

A constructor with labeled fields may be used to construct a value in which the components are specified by name rather than by position. Unlike the braces used in declaration lists, these are not subject to layout; the { and } characters must be explicit. (This is also true of field updates and field patterns.) Construction using field labels is subject to the following constraints: [...]

  • Fields not mentioned are initialized to ⊥.

  • A compile-time error occurs when any strict fields (fields whose declared types are prefixed by !) are omitted during construction.

因此它是语言规范的一部分,编译器必须接受该代码。所有字段均已初始化,仅部分字段使用 undefined 进行初始化。

foo = Foo{ one = 5 }

相当于

foo = Foo 5 undefined

如果你要求的话,一个好的编译器会警告你。如果您想要错误,请严格指定字段。

关于haskell - 为什么要对该记录进行类型检查?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14611566/

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