This is a read-only archive of lispforum.com. The forum was locked to new users and posts and is preserved here as static HTML from a database snapshot taken on 2019-09-07.

SICP Exercise related Question

3 posts · 2269 views

Hi all,

I just started learning to program in LISP. I stumbled upon this question when I was going through the SICP exercises.

1. The following always return b ; I suppose this is because + here is not treated as a function
(defun a-plus-abs-b (a b)
(if (> b 0) + -) a b)

2. However I can't get the following to work as well ...
(defun a-plus-abs-b (a b)
(if (> b 0) #'+ #'-) a b)

Thanks for your 'gyan' ..

Cheers,
Nanda

Re: SICP Exercise related Question

(defun a-plus-abs-b (a b)
	   (funcall (if (> b 0) '+ '-) a b))
SICP examples are in scheme, scheme is so-called lisp-1 and common lisp is lisp-2 (common lisp has different namespaces for functions and variables) ...

Re: SICP Exercise related Question

nandakishor_koka wrote:1. The following always return b ; I suppose this is because + here is not treated as a function
(defun a-plus-abs-b (a b)
(if (> b 0) + -) a b)

2. However I can't get the following to work as well ...
(defun a-plus-abs-b (a b)
(if (> b 0) #'+ #'-) a b)
1. The body of the function contains 3 expressions: (if (> b 0) + 0), a, b. They are evaluated in sequence, and the result of evaluting the last expression is returned. In this case, b is always evaluated last, so b is returned. In Scheme, you would write the body of the function as ((if (> b 0) + -) a b) (notice the additional parenthesis around the three expression).
2. Scheme and Common Lisp have different rules of evaluating expressions. So, in Common Lisp it is an error to write ((if (> b 0) + -) a b), because the first item of the form can be only name of the function or lambda, but not the other form that would return the function. The solution is to funcall: (funcall (if (> b 0) #'+ #'-) a b). Funcall takes function and its arguments and evaluates the function.