Re: List to hash/dict?
- From: Marcin 'Qrczak' Kowalczyk <qrczak@xxxxxxxxxx>
- Date: Sat, 27 Aug 2005 12:35:48 +0200
Mike Austin <no@xxxxxxxx> writes:
> I noticed the different styles of anonymous functions in your code and
> the one on the web page:
>
> sortBy (\(_,x) (_,y) -> compare x y)
>
> sortBy (\a b -> snd b `compare` snd a)
>
> Is it simply that, a style, or is there something deeper?
In this case I would say it's a style, but they are not technically
equivalent because Haskell is lazy.
In the first version the comparator evaluates both arguments (pairs)
and passes their second components to compare.
In the second version the comparator passes to compare two expressions
which, when evaluated, evaluate the arguments and extract their second
components.
The function 'compare' is dispatched basing on the type of values
being compared. If the the type of the second components is fixed in
this place of the program, or if this place is decided worth inlining
or specializing, then an optimizing compiler will notice that
comparison for this type is strict (i.e. always needs values of both
arguments) and generate the same code for both versions. Comparisons
are usually strict by their nature.
But if this call site is polymorphic, the compiler can't a priori
assume that 'compare' will evaluate both arguments, it's just a
function, so the comparator passes to 'compare' lazy thunks which
will evaluate arguments of the comparator and extract its second
components when they are themselves evaluated.
So if the comparison is indeed strict but the compiler doesn't
know the type, the first version might generate better code.
In an artificial case when it's not strict, the first version will
unnecessarily evaluate pairs which are not evaluated by the second
version and thus in theory be slower or fail to terminate.
--
__("< Marcin Kowalczyk
\__/ qrczak@xxxxxxxxxx
^^ http://qrnik.knm.org.pl/~qrczak/
.
- References:
- List to hash/dict?
- From: Anonymous
- Re: List to hash/dict?
- From: Ketil Malde
- Re: List to hash/dict?
- From: Lutz Donnerhacke
- Re: List to hash/dict?
- From: Mike Austin
- List to hash/dict?
- Prev by Date: Re: List to hash/dict?
- Next by Date: Re: LtU down?
- Previous by thread: Re: List to hash/dict?
- Next by thread: Re: List to hash/dict?
- Index(es):
Relevant Pages
|