Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using AND with the apply function in Scheme

Tags:

scheme

Why doesn't the following work?

(apply and (list #t #t #f))

While the following works just fine.

(apply + (list 1 3 2))

This seems to be the case in both R5RS and R6RS?

like image 983
btw0 Avatar asked Dec 22 '08 23:12

btw0


People also ask

What does apply function do in Scheme?

• apply takes a function & a list of arguments for it & returns the result of applying the function to them. > (apply + ' (1 2 3)) 6. • It can be given any number of arguments, so long as.

How do you call a function in another Scheme?

A function call is written as (f args) where f is the name of the function and args a space-separated sequence of arguments. So to call tab without arguments, you'd write (tab) and to call translate with the argument x , you'd write (translate x) .

What does cons do in Scheme?

The other constructor, cons , is used when you already have a list and you want to add one new element. Cons takes two arguments, an element and a list (in that order), and returns a new list whose car is the first argument and whose cdr is the second.

What is eval in Scheme?

In DrScheme, the eval function takes a Scheme object, and evaluates the Scheme object. ( It can also take a second argument, which is an environment. This is actually what is specified in the R5 spec.)


3 Answers

and isn't a normal function because it will only evaluate as few arguments as it needs, to know whether the result is true or false. For example, if the first argument is false, then no matter what the other arguments are, the result has to be false so it won't evaluate the other arguments. If and were a normal function, all of its arguments would be evaluated first, so and was made a special keyword which is why it cannot be passed as a variable.

like image 72
Paige Ruten Avatar answered Nov 11 '22 08:11

Paige Ruten


(define and-l (lambda x 
    (if (null? x)
        #t
        (if (car x) (apply and-l (cdr x)) #f))))

pleas notice that this is lambda variadic! apply example (and-l #t #t #f)

or you can use it via apply procedure(as was asked) for example (apply and-l (list #t #t #f))

both options are ok...

like image 29
Alex v Avatar answered Nov 11 '22 07:11

Alex v


and is actually a macro, whose definition is outlined in R5RS chapter 4. The notation "library syntax" on that page really means it is implemented as a macro.

Section 7.3, Derived expression types gives a possible definition of the and macro:

(define-syntax and
  (syntax-rules ()
    ((and) #t)
    ((and test) test)
    ((and test1 test2 ...)
     (if test1 (and test2 ...) #f))))

Given this defintion, it is not possible to use and as a function argument to apply.

like image 39
Greg Hewgill Avatar answered Nov 11 '22 07:11

Greg Hewgill