The amb statement as a macro or procedure?

In this page there is a comment after the report, which gives a very short realization ambas procedure:

(define (amb-backtrack)
  (error "no solution found"))

(define (amb . args)
  (call/cc (lambda (return)
             (let ((backtrack amb-backtrack))
               (map (lambda (x)
                      (call/cc (lambda (k)
                                 (set! amb-backtrack k)
                                 (return x))))
                    args)
               (backtrack 'fail)))))

But I usually see ambimplemented as a macro - in the schemers.org FAQ, as well as in the Dorai Sitaram book :

(define amb-fail '*)

(define initialize-amb-fail
  (lambda ()
    (set! amb-fail
      (lambda ()
        (error "amb tree exhausted")))))

(initialize-amb-fail)

(define-macro amb
  (lambda alts...
    `(let ((+prev-amb-fail amb-fail))
       (call/cc
        (lambda (+sk)

          ,@(map (lambda (alt)
                   `(call/cc
                     (lambda (+fk)
                       (set! amb-fail
                         (lambda ()
                           (set! amb-fail +prev-amb-fail)
                           (+fk 'fail)))
                       (+sk ,alt))))
                 alts...)

          (+prev-amb-fail))))))

So, the macro version is longer and a little harder to understand. I could not see any advantages over the version of the procedure, and, of course, I would prefer to use the procedure than the macro. Did I miss something?

+5
source share
1 answer

The difference is that a procedure call always evaluates all arguments.

(amb 1 (very-expensive-computation))

amb very-expensive-computation, 1. 1 , , . , @Eli Barzilay , amb , .

, , Prolog.

+6

All Articles