Composing Fexprs Preserves Short-circuit Evaluation.
; One of the well known advantages of special operators over
; functions is that special operators apply "short-cuirciting".
;
; For example, operator "and" that evaluates
;
; (and (= 1 1) (= 2 2) (= 3 4) (= 5 (slow-function 6)))
;
; will never evaluate clause (= 5 (slow-function 6)). Instead,
; after (= 3 4) is recognized to be false, there is no theoretical
; possibility that whole expression evaluates to true, and
; nil is returned without evaluating other clauses.
;
; This is significant difference between operators and functions.
; If "and" was defined as function, all clauses would be evaluated
; first, and then passed to the operator "and."
;
; Only today I came to idea to test whether operator compose I
; defined few days ago, which can be applied on fexprs as well as
; on functions, preserves short-circuiting.
;
; I'll test it by defining two well known logical operators,
; nor and nand.
(set 'nor (compose not or))
(set 'nand (compose not and))
; Let us test whether 'nor' and 'nand' preserve short-circuit
; evaluation.
(nand (println "this should be done ")
(println "and this should be done")
(println (setf j nil))
(println "but this shouldn't be done"))
; this should be done
; and this should be done
; nil
;
(println "---")
(nor (println (= 1 2))
(println (= 1 3))
(println "and something different")
(println "this shouldn't be done"))
; ---
; nil
; nil
; and something different
; Everything works. Beautiful, isn't it?
(exit)
Bad weather in Croatia.
Subscribe to:
Post Comments (Atom)
Really bad weather :(
ReplyDelete>Beautiful
compose() is a good enough approach to make code shorter, I like it :)
Actually, it is not that bad weather if one sits in the bar, drink tea and rum, and watch the world through windows. I have another similar function, it is "increase-order". On that way I can increase order of functions, so these can apply on other functions. For example, I can define +f
ReplyDelete(setf +f (increase-order +))
and +f will add functions, not numbers.
((+f sin cos) x) ==> (+ (sin x) (cos x))
It was one of my first posts, so maybe it doesn't work any more - Newlisp changed, but version in my library works.
Blogger Wolverrum said...
ReplyDeleteAs I understanding increasOrder properly it has type:
increaseOrder :: (b->c) -> ((a->b) -> (a->c))
At least above I was able to create using C#2 :)
FuncX<FuncX<A, B>, FuncX<A, C>> Up< B, C>(FuncX<B, C> fn)
{return delegate(FuncX<A, B> h) {
return Compose(h, fn); }; }
Hey, its pretty elegant solution.
ReplyDelete