为什么会有“数据"?和“新型"在哈斯克尔? [英] Why is there "data" and "newtype" in Haskell?

查看:26
本文介绍了为什么会有“数据"?和“新型"在哈斯克尔?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看起来 newtype 定义只是一个遵守一些限制(例如,只有一个构造函数)的 data 定义,并且由于这些限制,运行时系统可以更有效地处理 newtype .对未定义值的模式匹配处理略有不同.

It seems that a newtype definition is just a data definition that obeys some restrictions (e.g., only one constructor), and that due to these restrictions the runtime system can handle newtypes more efficiently. And the handling of pattern matching for undefined values is slightly different.

但是假设 Haskell 只知道 data 定义,没有 newtypes:编译器不能自己找出给定的数据定义是否遵守这些限制,并自动更有效地对待它?

But suppose Haskell would only knew data definitions, no newtypes: couldn't the compiler find out for itself whether a given data definition obeys these restrictions, and automatically treat it more efficiently?

我确定我错过了一些东西,这一定有更深层次的原因.

I'm sure I'm missing out on something, there must be some deeper reason for this.

推荐答案

newtype 和单构造器 data 都引入了单值构造器,但是引入了值构造器by newtype 是严格的,而 data 引入的值构造器是惰性的.所以如果你有

Both newtype and the single-constructor data introduce a single value constructor, but the value constructor introduced by newtype is strict and the value constructor introduced by data is lazy. So if you have

data D = D Int
newtype N = N Int

然后 N undefined 等价于 undefined 并在计算时导致错误.但是D undefinednot等价于undefined,只要你不去往里面偷看就可以评估.

Then N undefined is equivalent to undefined and causes an error when evaluated. But D undefined is not equivalent to undefined, and it can be evaluated as long as you don't try to peek inside.

编译器不能自己处理这个问题.

Couldn't the compiler handle this for itself.

不,实际上并非如此—在这种情况下,作为程序员,您可以决定构造函数是严格的还是惰性的.要了解何时以及如何使构造函数变得严格或惰性,您必须比我对惰性求值有更好的理解.我坚持报告中的想法,即 newtype 可让您重命名现有类型,例如具有几种不同的不兼容测量:

No, not really—this is a case where as the programmer you get to decide whether the constructor is strict or lazy. To understand when and how to make constructors strict or lazy, you have to have a much better understanding of lazy evaluation than I do. I stick to the idea in the Report, namely that newtype is there for you to rename an existing type, like having several different incompatible kinds of measurements:

newtype Feet = Feet Double
newtype Cm   = Cm   Double

两者在运行时的行为与 Double 完全一样,但编译器承诺不会让您混淆它们.

both behave exactly like Double at run time, but the compiler promises not to let you confuse them.

这篇关于为什么会有“数据"?和“新型"在哈斯克尔?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆