Implementing ?: in Python
Python (at least up to version 2.4) doesn’t have a much needed ?: operator. Here’s how you can hack it yourself (I’m not sure if I would use it, except for very special situations, though).
# if-then-else function taking functions as arguments.
def ite(condition, true, false):
if condition:
return true()
else:
return false()
# Call it like this.
ite(condition, lambda:arg_true, lambda:arg_false);
# Just to check if it really works
def fun(arg):
print "Evaluated "+str(arg)
return arg
print ite(0, lambda:fun(1), lambda:fun(0));
print ite(1, lambda:fun(1), lambda:fun(0));
November 28th, 2006 at 11:12 pm
Fun to note that
print ite(0, lambda:fun(fun(1)), lambda:fun(fun(0))); print ite(1, lambda:fun(fun(1)), lambda:fun(fun(0)));
is also lazy. For that matter…
#!/usr/bin/ruby
def ife(condition,iftrue,iffalse) if condition return iftrue.call else return iffalse.call end end
def debug(x) puts “Debug “+x.to_s return x end
ife(true, lambda {debug(debug(true))},lambda{debug(debug(false))}) ife(false, lambda {debug(debug(true))},lambda{debug(debug(false))})
works.
Or the less sugary (no need for lambda wrapper) and generalized version in scheme:
(define (debug x) (let () (display “debug: “) (display x) (display “\n”) x))
(debug (list (debug “one”) (debug “two”) (debug “three”) (debug “four”) (debug “five”)))
(display “\nversus…\n\n”)
(define-syntax nth (syntax-rules () ((nth n var) var) ((nth n var rest …) (if (= n 0) var (nth (- n 1) rest …)))))
(nth 0 (debug “one”) (debug “two”) (debug “three”) (debug “four”) (debug “five”)) (display “\nor\n\n”) (nth 1 (debug “one”) (debug “two”) (debug “three”) (debug “four”) (debug “five”))
yields
$ scheme ife.scm debug: one debug: two debug: three debug: four debug: five debug: (one two three four five)
versus…
debug: one
or
debug: two $
How I miss real macros. ;^(
November 29th, 2006 at 8:17 pm
Cool. Apparently Python 2.5 offers conditional expressions with a very weird syntax.
ratio = x/y if x > y else y/x
The condition is in the middle:
result = true_value if condition else false_value
The benefit of this syntax is that you can read it just like English, which is a quality I like in a language. The official excuse/explanation is that in the standard library most conditional expressions evaluate 90 percent of the time to |True| so the |true_value| should dominate.
I am not sure if I like it though…