在模式中重用列表
当我写:
sort [x] = [x]
编译器是否足够聪明以重用相同的列表,或者我是否必须明确说明它?
sort xs@[_] = xs
When I write:
sort [x] = [x]
Is the compiler smart enough to reuse the same list, or do I have to be explicit about it?
sort xs@[_] = xs
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它足够聪明吗?让我们来看看!
这是 STG:
有趣的是这一行:
我们看到我们正在为
x_sdV
和[]
创建一个新的 cons-cell。所以,不。不过,这还不算太糟糕,因为 x_sdV 本身是共享的,所以它只是一个构造函数;此外,我们正在强制列表的主干xs
,因此GHC无论如何都需要重写它。所以不用担心。Is it smart enough? Let's see!
Here is the STG:
The interesting bit is this line:
where we see that we are creating a new cons-cell for
x_sdV
and[]
. So, no. However, this is not too bad, becausex_sdV
itself is shared, so it’s only a single constructor; furthermore, we are forcing the spine of the listxs
, so GHC would need to rewrite it anyway. So don't worry about it.