Problem in COND

Discussion of Common Lisp

Problem in COND

Postby mparsa » Mon Jun 25, 2012 6:20 am

Hi,
I am quit new in lisp programming. I wrote a simple program but It gives me an error when I try to run it.
I think the problem is the way that I call the function but I don't know how to solve it.
I want to have something like switch case in lisp. And this is my program:
(defun test (var)
(cond
((= var "foo")
(message "This is the foo block."))
((= var "bar")
(message "This is the bar block."))
(t
(message "Default case")
)))
(test ("foo"))
Anybody can help?
Thank you.
mparsa
 
Posts: 26
Joined: Mon Jun 25, 2012 6:15 am

Re: Problem in COND

Postby wvxvw » Mon Jun 25, 2012 9:27 pm

You can't add extra parens in Lisp, like you could do it in C-like languages. In Lisp parens mean you are calling a function. So, in the line (test ("foo")) you are saying this:
call function test with the result of calling function "foo", but "foo" isn't even a function, it is an array of characters (a string), and it's not callable. What you want to do is (test "foo"), i.e. call function test with an argument "foo".
wvxvw
 
Posts: 125
Joined: Sat Mar 26, 2011 6:23 am

Re: Problem in COND

Postby mparsa » Tue Jun 26, 2012 12:37 am

Hi, Thank you for your help :)
I also use "foo" without parens. like ( test "foo") but it gave me an error :
Error: `"foo"' is not of the expected type `number'
[condition type: type-error]
Do you know what is the problem ? Can we use string as a variable in lisp ?
mparsa
 
Posts: 26
Joined: Mon Jun 25, 2012 6:15 am

Re: Problem in COND

Postby mparsa » Tue Jun 26, 2012 12:45 am

For example when I change my program to the below one, it works. In the below one I just use integer besides string. Is there any way that I use string ?
(defun test (var)
(cond
((= var 1)
(print "This is the foo block.")
(print "yes"))
((= var 2)
(message "This is the bar block."))
(t
(message "Default case")
)))
(setf k 1)
(test k)
mparsa
 
Posts: 26
Joined: Mon Jun 25, 2012 6:15 am

Re: Problem in COND

Postby JamesF » Tue Jun 26, 2012 12:49 am

The problem is that you're using the wrong comparator. Try 'equal' or 'equalp' instead of '='.
JamesF
 
Posts: 95
Joined: Thu Jul 10, 2008 7:14 pm

Re: Problem in COND

Postby mparsa » Tue Jun 26, 2012 1:12 am

Thanks a lot. It is working now with "equal". :)
mparsa
 
Posts: 26
Joined: Mon Jun 25, 2012 6:15 am


Return to Common Lisp

Who is online

Users browsing this forum: No registered users and 2 guests