Forgive me if I am wrong, but I believe that section 1 contains mistakes. In the implementations of evens_only, shouldn't both of the places where modulus is used be preceded by "not"?
This isn't meant to detract from the truth that "Beautiful [code] is better than ugly," I merely thought the implementation should be correct.
Yeah, I don't think you can use i % 2 as an equivalent of i % 2 == 0. Maybe it's a python 3 thing, but on my 2.6.1 the mod operator just returns the remainder, it doesn't change its output if it's a boolean context (which would be perlish and highly unpythonic).
I think i % 2 is just straight up incorrect.
If we're talking about style, I think i % 2 == 0 is much more clear than (not i % 2). It says explicitly that the remainder of i divided by 2 is 0.
> Yeah, I don't think you can use i % 2 as an equivalent of i % 2 == 0. Maybe it's a python 3 thing, but on my 2.6.1 the mod operator just returns the remainder, it doesn't change its output if it's a boolean context (which would be perlish and highly unpythonic).
$ python3
>>> not 0
True
Python doesn't have Perl-like contexts, but it does treat lots of values as True or False. I do agree that
I agree. Using the truthiness of non-boolean values has always seemed questionable in any language (Javascript is possibly the worst offender). For many statically typed languages this is caught as a syntax error, which is nice for those of use prone to occasionally typos.
The boolean equivalents of non-boolean values are well-defined and fairly simple in Python, and I believe it's encouraged (or at least extremely common) to use them as such.
In Haskell this is caught as a type error. But you can make your own version:
class ExtendedBool t where
toBool :: t -> Bool
instance ExtendedBool Int where
toBool = (0/=)
instance ExtendedBool [a] where
toBool = not . null
if' v a b =
if (toBool v)
then a
else b
main = if' "String"
(print "True")
(print "False")
It seems to work in older Python versions (tested with 2.5).
I think the new implementation is more natural:
even%2 = 0, and 0 is false, while uneven%2 = 1, and 1 is true.
This isn't meant to detract from the truth that "Beautiful [code] is better than ugly," I merely thought the implementation should be correct.