[Haskell-beginners] Definition of last: why complicate it?
daniel.is.fischer at googlemail.com
Fri Apr 4 19:53:17 UTC 2014
On Friday 04 April 2014, 20:12:50, Rudy Matela wrote:
> According to a stackoverflow answer , this should be done
> automatically by GHC. Why it's still defined like that I don't know:
> maybe because the code is for when using other compilers, or maybe I
> misinterpreted the stackoverflow post and GHC is not able to do that.
One can check that, just copy the source (hiding Prelude.last or renaming it)
and compile, with -ddump-simpl to get the core GHC produces (it takes a little
practice to read core, but it's sufficiently similar to Haskell to start
understanding much of it quickly).
With -O2, all GHC versions I tried (6.12.3, 7.0.2, 7.2.2, 7.4.2, 7.6.1, 7.6.3)
produced (almost¹) the more efficient version from the USE_REPORT_PRELUDE
source, but with only -O, none did.
If the libraries are guaranteed to be compiled with -O2 when building the
compiler, there would be no need for the other source. But since that is not
guaranteed, it's better to manually write the better version.
Footnote (¹): what GHC produces with -O2 is slightly different, it tests for a
singleton list once in the wrapper before the worker is called, but it also
creates a rule that when it is called on a list that is known at compile-time
to be nonempty, the worker shall be called directly.
More information about the Beginners