【问题标题】:Strict single-constructor single-field data declaration vs. newtype严格的单构造函数单字段数据声明 vs. newtype
【发布时间】:2014-02-15 03:44:42
【问题描述】:

Difference between `data` and `newtype` in Haskell 和其他几个问题解决了 data 和 newtype 之间的一般差异。我的问题是一个非常具体的问题。如果G是某种类型,有什么区别

data T = T !G

newtype T = T G?

它们似乎具有相同的严格属性,我不明白为什么编译器有任何理由对它们进行不同的编译,但也许我遗漏了一些东西。

【问题讨论】:

  • 您的问题已回答on the wiki
  • !!G 中代表什么?

标签: haskell


【解决方案1】:

我要回答一个稍微不同的问题:“newtype 是否向 Haskell 添加任何 语义 功能?”。我相信答案是“不”。

假设我们有data Td = Td !Gnewtype Tn = Tn G。那么

  • TdTn 拥有完全相同的居民,即 G 的居民
  • 当强制使用 WHNF 时,两者的行为方式相同:它们“包含”的 g 是强制的
  • 它们与case 交互的方式不同,但这只是句法。这两个版本之间有直接对应关系。

下表说明了如何在 case 语句中将 newtype Tn 替换为 data Td。反过来也有翻译。

Tn                                    Td

case tn of _ -> ...                   case td of _ -> ...
case tn of Tn _ -> ...

case tn of Tn x -> ... x ...          let x1 = case tn of Td x -> x in ... x1 ...

case tn of x -> ... x ...             case td of x -> ... x ...

case tn of Tn x -> x `seq` ...        case td of Td _ -> ...         

case tn of Tn x -> x `seq` ... x ...  case td of Td x -> ... x ...     

所以从语义上讲,我相信 Haskell 可以避免添加 newtype。从语法上讲 newtype 可能会使case 语句不那么尴尬,仅此而已。

【讨论】:

  • Td 同时拥有bottomT bottom,而Tn 只有T bottom
  • TdbottomTd bottom 中无法区分。
  • case td of Td _ -> "whee"
  • @SebastianRedl:你想说什么?注意这里G是一个严格的数据字段,所以case td of Td _强制它。
【解决方案2】:

主要区别在于它的编译方式。所有data 声明introduce memory overhead,而newtype 不声明。

这是内存占用测量库的输出。

import GHC.DataSize

data A = A !Int
newtype B = B Int

main = do
  print =<< (recursiveSize $! A 1)
  print =<< (recursiveSize $! B 1)
  print =<< (recursiveSize $! 1)

输出:

32
16
16

Shachaf 在第一条评论中提到了另一个区别。

【讨论】:

  • 语义不同:case undefined of A _ -&gt; ()undefinedcase undefined of B _ -&gt; ()()
  • @schachaf 哇,这是我不知道的案例。谢谢。
  • @shachaf,我认为你一针见血。我猜对新类型的模式匹配是无操作的,而对严格数据类型的模式匹配是一种强制。
  • !!Int 中代表什么?
  • @AlexanderSupertramp 它声明应该严格评估该字段而不是惰性评估(默认值)。在newtype 包装器的情况下,包装的类型只能是严格的,所以那里不需要爆炸。
猜你喜欢
  • 2016-06-18
  • 2023-04-05
  • 2016-05-16
  • 1970-01-01
  • 2020-09-13
  • 2013-08-14
  • 2016-02-22
  • 2022-01-15
  • 2016-12-16
相关资源
最近更新 更多