Using delay/force to implement control structures in the absence of macros?
Using Scheme the programming language, how would one use delay/force to implement control structures without resorting to using macro facilities?
Thank you.开发者_如何学编程
Most programming languages support control-flow structures that don't evaluate arguments redundantly.
so (and (expression_1) ... (expression_N))
would return #f
as soon as the first false expression is found.
If and
were simply a function in Scheme, all of it's parameters would have been evaluated before getting to the body of and
's implementation. There's no way you could implement it to get around this.
Macros don't evaluate their arguments, they just rewrite terms before they get evaluated. You can take advantage of that to create control structures like if/cond/or/and as long as you have one of them to work with already. In fact, because a lambda body isn't evaluated until called, all you really need for lazily evaluated control flow statements are lambda and macros.
Now, if you don't want to use macros, then your arguments will be evaluated. You have to wrap them up in lambdas, or you can use delay/force. But then you aren't passing expressions into your control structure. You're passing in expressions wrapped in something. It gets kinda ugly.
Here is a contrived example using lambdas.
(define bool1
(lambda ()
(display "evaluating bool1\n")
#t))
(define bool2
(lambda ()
(display "evaluating bool2\n")
#t))
(define (_or b1 b2)
(if (b1) #t
(if (b2) #t #f)))
(define (_and b1 b2)
(if (b1) (if (b2) #t #f) #f))
usage:
> (_and bool1 bool2)
evaluating bool1
evaluating bool2
#t
> (_or bool1 bool2)
evaluating bool1
#t
>
精彩评论