Schwartzian transform

Dermot paikkos at gmail.com
Wed Aug 13 13:03:40 BST 2014


On 13 August 2014 12:17, Aaron Crane <perl at aaroncrane.co.uk> wrote:

> Dermot <paikkos at gmail.com> wrote:
> > my $count = 1;
> > my @sorted =
> >     map { $ref->{ $_->[0] }->{position} = $count++; $ref->{ $_->[0] } }
> >     sort { $a->[1] <=> $b->[1] }
> >     map [ $_, $ref->{$_}->{position} ],
> >     keys %{ $ref };
>
> It's not clear to me that the Schwartzian Transform adds anything to
> this code: with it, you have to create an array ref for every input
> hash ref, and then sort by an element of each array ref, but without
> it, you could simply sort by an element of each input hash ref:
>
> my @sorted = sort { $a->{position} <=> $b->{position} } values %$ref;
> ...
> If you don't actually need to keep @sorted around, the whole thing can
> be even simpler:
>
> my $position = 1;
> $_->{position} = $position++
>     for sort { $a->{position} <=> $b->{position} } values %$ref;
>
> I've also renamed your $count variable to $position, because I think
> that more accurately reflects what it contains.
>
>
I agree with everything you said. It was pure instinct to reach for map()
and thereafter it was the challenge that interested me. The version you and
Mark have posted is by far clearer and I suspect more efficient.
Thank you.
Dermot.


More information about the london.pm mailing list