Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why (apply and '(1 2 3)) doesn't work while (and 1 2 3) works in R5RS? [duplicate]

Tags:

lisp

scheme

I tried it in Racket like this

> (apply and '(1 2 3))
. and: bad syntax in: and
> (and 1 2 3)
3

Does anyone have ideas about this?

like image 811
Hanfei Sun Avatar asked Jun 21 '13 09:06

Hanfei Sun


1 Answers

and is not a function, it's a macro, so you cannot pass it around like a function.

The reason and is a macro, is to enable short-circuiting behaviour. You can make your own non-short-circuiting version:

(define (my-and . items)
  (if (null? items) #t
      (let loop ((test (car items))
                 (rest (cdr items)))
        (cond ((null? rest) test)
              (test (loop (car rest) (cdr rest)))
              (else #f)))))

and my-and can be used with apply.

For comparison, here's what the macro (which does do short-circuiting) looks like:

(define-syntax and
  (syntax-rules ()
    ((and) #t)
    ((and test) test)
    ((and test rest ...) (if test
                             (and rest ...)
                             #f))))
like image 116
Chris Jester-Young Avatar answered Nov 15 '22 09:11

Chris Jester-Young