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
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
Is it smart enough? Let's see!
ezyang@javelin:~$ cat Foo.hs
module Foo where
foo [x] = [x]
Here is the 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]
The interesting bit is this line:
[] -> : [x_sdV GHC.Types.[]];
where we see that we are creating a new cons-cell for x_sdV
and []
. So, no. However, this is not too bad, because x_sdV
itself is shared, so it’s only a single constructor; furthermore, we are forcing the spine of the list xs
, so GHC would need to rewrite it anyway. So don't worry about it.
© 2022 - 2024 — McMap. All rights reserved.