Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is cond a special form in Scheme, rather than a function?

(defun triangle-using-cond (number)
  (cond 
    ((<= number 0) 0) ; 1st
    ((= number 1) 1)  ; 2nd
    ((> number 1)     ; 3rd
      ;; 4th
      (+ number
         (triangle-using-cond (1- number))))))

Things that I know about Cond

  • It allows multiple test and alternative expressions
  • It has pre-specified evaluation order. For instance, the first condition will always evaluated whether it is right or not

One thing that I cannot distinguish is that what makes cond different from a function!

like image 320
user2884707bond Avatar asked Nov 01 '15 18:11

user2884707bond


People also ask

What does cond do in Scheme?

cond works by searching through its arguments in order. It finds the first argument whose first element returns #t when evaluated, and then evaluates and returns the second element of that argument.

Does cond need else Scheme?

The else clause of a cond is optional; if present, that branch will be taken "by default"---if none of the other conditions evaluates to a true value, the else branch will be taken.

What is an expression in Scheme?

A Scheme expression is a construct that returns a value, such as a variable reference, literal, procedure call, or conditional. Expression types are categorized as primitive or derived. Primitive expression types include variables and procedure calls.

Is lambda a special form?

Lambda is the name of a special form that generates procedures.


1 Answers

A function call (e0 e1 e2) is evaluated like this

1. e0 is evaluated, the result is (hopefully) a function f
2. e1 is evaluated, the result is a value v1
3. e2 is evaluated, the result is a value v2
4. The function body of `f` is evaluated in an environment in which
   the formal parameters are bound to the values `v1` and `v2`.

Note that all expressions e0, e1, and, e2 are evaluated before the body of the function is activated.

This means that a function call like (foo #t 2 (/ 3 0)) will result in an error when (/ 3 0) is evaluated - before control is handed over to the body of foo.

Now consider the special form if. In (if #t 2 (/ 3 0)) the expressions #t is evaluated and since the value non-false, the second expression 2 is evaluated and the resulting value is 2. Here (/ 3 0) is never evaluated.

If in contrast if were a function, then the expressions #t, 2, and, (/ 3 0) are evaluated before the body of is activated. And now (/ 3 0) will produce an error - even though the value of that expressions is not needed.

In short: Function calls will always evaluate all arguments, before the control is passed to the function body. If some expressions are not to be evaluated a special form is needed.

Here if and cond are examples of forms, that don't evaluate all subexpressions - so they they need to be special forms.

like image 166
soegaard Avatar answered Oct 23 '22 14:10

soegaard