develooper Front page | perl.perl5.porters | Postings from July 2012

Re: Smartmatch two cents (was... List::Util... when...)

Thread Previous | Thread Next
From:
Aaron Crane
Date:
July 3, 2012 10:34
Subject:
Re: Smartmatch two cents (was... List::Util... when...)
Message ID:
CACmk_tvrNrva2CV6EcnTYFXv9uSoRufd95fYzkVMkDcmj0o3sQ@mail.gmail.com
Ed Avis <eda@waniasset.com> wrote:
> David Mertens asked:
>>Why would "$a in %hash" be equivalent to "exists $hash{$a}"?
>
> This is how it works in Python, and it seems natural in Perl too.

It doesn't seem particularly natural to me: I find it bletcherous
that, in Python, you can't statically tell the difference between an
O(1) dict-existence test and an O(N) sequence-containment test (let
alone a sequence-subsumption test).  Given that we already have a
perfectly cromulent operator for testing hash existence, and that the
existing builtins that DWIM between array refs and hash refs aren't
widely liked, I'm inclined to think that, if we acquire such an `in`
operator, it shouldn't allow a hash on its RHS.

Beyond that, I'm not at all convinced that this `in` is powerful
enough to justify its own existence (regardless of whether it
replicates the behaviour of `exists` on a hash).  If it can only do
string comparison, there are a variety of common tasks where you have
to write out a longhand equivalent anyway; if it guesses as to whether
you meant string equality or numeric equality or regex match or what
have you, then it repeats essentially all the problems of smartmatch
as currently implemented.

The more I consider this, the more strongly I think that a wordier API
is the right thing — along the lines of Test::Deep (now maintained by
our fearless pumpking) or Leon's Smart::Match.  I offer the following
anecdotal support for this position.  I currently have a codebase
which makes substantial use of List::MoreUtils::any and friends for
higher-order list-wise tests.  By my reckoning, only about one
occurrence in ten could be refactored to use an `in` operator of the
form you suggest; but every single occurrence can be refactored to use
Smart::Match (and almost all of them are made much clearer by doing
so).

-- 
Aaron Crane ** http://aaroncrane.co.uk/

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About