Page 1 of 1

SICP Exercise related Question

Posted: Fri Jan 09, 2009 11:36 am
by nandakishor_koka
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

Posted: Fri Jan 09, 2009 4:31 pm
by makia

Code: Select all

(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

Posted: Sat Jan 10, 2009 1:16 am
by dmitry_vk
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.