We discussed the ability to define new control structures in functional programming languages today in class, and the example given was a while-loop construct in Scheme. The while was a function which mapped one state to another and had to accept as its test and body parameters functions of zero arguments, because otherwise Scheme's strict evaluation would defeat the purpose of the loop. I mentioned macros but we didn't really go into them, so I thought I would give an example of an alternate way of writing a while loop in Scheme, which leads to a pretty different style.
(define-macro while (lambda (test . body)
(let ((loop (gensym)))
`(letrec ((,loop (lambda ()
(if ,test
(begin ,@body (,loop))))))
(,loop)))))
Then, to do the powers-of-two example, you would have to write something like
(define (powers2 exp)
(let ((result 1))
(while (> exp 0)
(set! result (* result 2))
(set! exp (- exp 1)))
result))
The primary differences here are that the loop is no longer a function mapping states to states, and the body of the loop is much more in an assignment-oriented, declarative style.
|
to: