Hacker News new | ask | show | jobs
by rheeseyb 4902 days ago
"Nothing is evaluated unless necessary

head (sort ls)

The list will only be sorted enough to find the minimum"

This may be technically true, but is a pretty bad example with much hand waving - what exactly does it mean to be "sorted enough to find the minimum" given that Haskell uses a merge sort implementation internally?

A better example of Haskell's lazy nature (taken from the Learn You A Haskell book) would be:

take 10 (repeat 5) - it's very easy to comprehend taking the first 10 elements of an infinitely long list without needing to compute the entire list.

1 comments

Yep, the "sort only to get head" trick only works fully with selection sort, where it reduces complexity from O(n^2) to O(n) (reduces to a simple max/min). But it also confers some advantage in the case of standard merge sort: the last two sorted sublists will not be merged.

Regarding "repeat", I find it pretty much awesome that it is implemented as a circular linked list with a single element, as in:

    repeat x = xs where xs = x : xs
which ensures that it will take up constant space no matter how "far" in it is evaluated.