On Friday, September 16, 2011 07:38 bearophile wrote:
> Jonathan M Davis:
> > Comparator functions are pretty much always binary predicates.
>
> And I think this has to change a bit in D. Because mapping functions are
> quite handy (despite requiring more memory, so it can't be the only way to
> do things in D, and both ways need to be supported).
>
> In Python3 sort/sorted/min/max don't take a comparator function, they only
> take a key mapping function.
>
> It's often used in Haskell too:
>
> import Data.List (sortBy)
> import Data.Ord (comparing)
> main = print $ sortBy (comparing length) [[1,3,1], [5], [7,7]]
Comparison is _by definition_ a multi-argument operation (and in most
programming languages it's a binary operation by definition, since they don't
allow you to chain comparison operations). Haskell's sortBy takes a binary
predicate, and in this case, you're using comparing is used to generate one
for you. But the it's still a binary predicate.
> > and taking simply the property to compare
> > would be extremely limiting.
>
> It gives some limitations in some uncommon cases (where using a comparator
> is better), but surely it's not 'extremely limiting'. I am using _only_
> key (mapping) functions in Python since years, and I am writing all kinds
> of programs with it.
>
> > For instance, what if you you wanted to compare
> > using two properties? That's completely straightforward with a binary
> > predicate and utterly impossible when you pass the property to be
> > compared instead of a proper predicate.
>
> It's extremely simple to do :-)
>
> (p){ return tuple(p.foo, p.bar); }
Okay. I didn't think of that (probably because I was thinking more in terms of
"length" than "a.length"), but is the overhead of creating a tuple to do that
warranted in a systems programming language? I sure wouldn't think so - not to
mention that the fact that max would then have to do something like
pred(a) < pred(b)
and thus call the predicate twice instead of the one function call that it
would be doing with a proper binary predicate. If you're lucky, the inliner
and optimizer would be able to reduce the extra overhead, but I'd be very
surprised if it were able to eliminate it.
Proper binary predicates just make way more sense IMHO.
- Jonathan M Davis