Super basic question about compiler optimization
I'm an absolute Haskell beginner. I got into a discussion recently with a friend about the following line of code:
last $ sort mylist
Would GHC generally optimize this to an O(n) linear search in practice? As a rule of thumb, how do you go about reasoning about compiler optimizations like this?
Thanks in advance!
Edit: fixed tail to last as pointed out by a commenter.
Posted Oct 19, 2018, 5:15 AM UTC · edited
Did you mean
head $ sort mylist? Or maybe usinglastinstead oftail?tailis unlikely to change the complexity. As a reminder,tailgives you back a list without the first element. In your example the list still has to be sorted in its entirety which is likely O(n log(n)). :-)For the version with
headthis would become equivalent to the functionminimum.Another comment mentions rewrite rules, I doubt there are rewrite rules for these cases around
sort(but I could be wrong). Depending on the sorting algorithm used, the rest of the list (thetail) might not necessarily need to be sorted thanks to laziness. That is, if the first element of the sorted list is known before the rest of the list is sorted, Haskell will "wait" before sorting the rest of the list until it's needed, which is never in theheadversion.Hope this helps! :-) Tell me if you have any questions.
Sorry, I meant last, not tail! Nice catch. You can see I'm a beginner.