(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
One thing that I cannot distinguish is that what makes cond different from a function!
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.
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.
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.
Lambda is the name of a special form that generates procedures.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With