class ToBool a where
toBool :: a -> Bool
if' :: ToBool a => a -> b -> b -> b
if' cond th el = if toBool cond then th else el
And add instances like these: instance ToBool Int where
toBool 0 = False
ToBool _ = True
instance ToBool String where
toBool "" = False
toBool _ = True
Or even: instance ToBool TimeStamp where
toBool = not . isMidnight
Lisp, of course, can do similar things via Macros.Some re-education should be enough.
This is a bit of a strawman, but being able to do
class Foo(object): def __bool__(self): return random.random() > 0.5
shows how crazy you could be. If you really want something weird, put it in the if-statement
That particular bit of craziness wouldn't be possible in Haskell. (Since that would require declared side-effects, and my interface above didn't have any declared.)
- you are doing something you shouldn't
- you are doing it in the wrong language
It's particularly bad because it is the kind of "clever" unnecessary code which is unlikely to see widespread adoption, clashes with existing conventions, and will eventually be disposed of after the author has left the company to pursue other opportunities.
Don't write clever code!
And this doesn't: if the `Int` in question is the exit status of a process, then 0 should be truthy and everything else falsy.
Better to make the test explicit. If the test is at all complex you wrap it up in its own function anyway, so it's not like it makes the if expression harder to read.
Consider also the instance for `Maybe`: which of these is right?
instance ToBool (Maybe a) where
toBool = isJust
instance ToBool a => ToBool (Maybe a) where
toBool = maybe False toBoolThere's some lifting approaches that construct those functions mostly automatically for you, as wrappers around the base functions on Booleans.