SICP Exercise related Question

Discussion of Common Lisp

SICP Exercise related Question

Postby nandakishor_koka » Fri Jan 09, 2009 11:36 am

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
nandakishor_koka
 

Re: SICP Exercise related Question

Postby makia » Fri Jan 09, 2009 4:31 pm

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) ...
makia
 
Posts: 25
Joined: Tue Jul 22, 2008 2:37 am

Re: SICP Exercise related Question

Postby dmitry_vk » Sat Jan 10, 2009 1:16 am

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.
dmitry_vk
 
Posts: 96
Joined: Sat Jun 28, 2008 8:01 am
Location: Russia, Kazan


Return to Common Lisp

Who is online

Users browsing this forum: Bing [Bot] and 3 guests

cron