gpt4 book ai didi

list - 在模式中重用列表

转载 作者:行者123 更新时间:2023-12-04 11:15:18 24 4
gpt4 key购买 nike

当我写:

sort [x] = [x]

编译器是否足够聪明,可以重用相同的列表,还是我必须明确说明?
sort xs@[_] = xs

最佳答案

它足够聪明吗?让我们来看看!

ezyang@javelin:~$ cat Foo.hs
module Foo where
foo [x] = [x]

这是STG:
ezyang@javelin:~$ ghc --make Foo.hs -ddump-stg -fforce-recomp
[1 of 1] Compiling Foo ( Foo.hs, Foo.o )

==================== STG syntax: ====================
Foo.foo =
\r srt:(0,*bitmap*) [ds_sdP]
let-no-escape {
fail_sdO =
sat-only \r srt:(0,*bitmap*) [ds1_sdN]
Control.Exception.Base.patError "Foo.hs:2:0-12|function foo";
} in
case ds_sdP of wild_sdY {
[] -> fail_sdO GHC.Prim.realWorld#;
: x_sdV ds1_sdT ->
case ds1_sdT of wild1_sdZ {
[] -> : [x_sdV GHC.Types.[]];
: ipv_se0 ipv1_se1 -> fail_sdO GHC.Prim.realWorld#;
};
};
SRT(Foo.foo): [Control.Exception.Base.patError]

有趣的是这一行:
                  [] -> : [x_sdV GHC.Types.[]];

我们看到我们正在为 x_sdV 创建一个新的 cons-cell和 [] .所以不行。不过,这还不算太糟糕,因为 x_sdV本身是共享的,所以它只有一个构造函数;此外,我们正在强制列表的脊椎 xs ,所以 GHC 无论如何都需要重写它。所以不用担心。

关于list - 在模式中重用列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5211192/

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