Combinator Logic
Combinator Logic

Reputation: 41

In LISP, what's the difference between "let" and "with"?

A simple example to show the differences in action would really help, since to me they both just seem interchangeable? Thanks :)

Upvotes: 3

Views: 203

Answers (2)

Elias Mårtenson
Elias Mårtenson

Reputation: 3895

They are indeed functionally equivalent.

In fact, at least SBCL expands any use of with in a loop macro invocation into an enclosing LET form.

Running the following:

(macroexpand '(loop with foo = 5 repeat 10 collect foo))

Results in the following expansion:

(BLOCK NIL
  (LET ((FOO 5))
    (LET ((#:LOOP-REPEAT-1681 (CEILING 10)))
      (DECLARE (TYPE INTEGER #:LOOP-REPEAT-1681))
      (SB-LOOP::WITH-LOOP-LIST-COLLECTION-HEAD (#:LOOP-LIST-HEAD-1682
                                                #:LOOP-LIST-TAIL-1683)
        (SB-LOOP::LOOP-BODY NIL
                            ((IF (<= #:LOOP-REPEAT-1681 0)
                                 (GO SB-LOOP::END-LOOP)
                                 (DECF #:LOOP-REPEAT-1681)))
                            ((SB-LOOP::LOOP-COLLECT-RPLACD
                              (#:LOOP-LIST-HEAD-1682 #:LOOP-LIST-TAIL-1683)
                              (LIST FOO)))
                            ((IF (<= #:LOOP-REPEAT-1681 0)
                                 (GO SB-LOOP::END-LOOP)
                                 (DECF #:LOOP-REPEAT-1681)))
                            ((RETURN-FROM NIL
                               (SB-LOOP::LOOP-COLLECT-ANSWER
                                #:LOOP-LIST-HEAD-1682))))))))

Upvotes: 1

Charlie Martin
Charlie Martin

Reputation: 112414

In Common Lisp, at least, you can only use with in the context of a loop macro. See the Common Lisp Hyperspec.

Upvotes: 1

Related Questions