gpt4 book ai didi

haskell - `newtype` 和 `data` 之间的区别,带有严格的注释

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

这段代码如何

data D = D { _d :: ![P] } -- Note the strictness annotation!

与此相比
newtype D = D { _d :: [P] }

answer to a related question说:

the main difference between data and newtype is that with data is that data constructors are lazy while newtype is strict



data 时,这种差异如何起作用?版本有严格的注释吗?

(问题基于我偶然发现的真实代码)

最佳答案

例如,

case undefined of
D d -> "hello"
data 会出错类型(严格或不严格),但将评估为 "hello"对于新类型。

这是因为,在运行时,应用 newtype构造函数,或对其进行模式匹配对应于无操作。甚至不强制我们 case之上。

相比之下, data 上的模式匹配构造函数总是强制我们的值 case之上。

我认为这是严格 data 之间唯一的运行时差异和 newtype .
有一些静态差异,例如一些 GHC 扩展只影响 newtype , Coercible等,但在运行时这两种类型是同构的(但模式匹配的操作方式不同,如上所示)。

关于haskell - `newtype` 和 `data` 之间的区别,带有严格的注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53391237/

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