Page 1 of 1

What's wrong with my code?

Posted: Thu Jul 08, 2010 12:21 pm
by joybee
Hello! I need help here.

The code I wrote:
setq mylist nil
setq a 3.5
setq b 4.2
setq str "test"
(cons (format nil "((a: ~f) (b: ~f) (mystring: ~a))" a b str) mylist)
setq a 5.6
setq b 7.8
setq str "hello"
(cons (format nil "((a: ~f) (b: ~f) (mystring: ~a))" a b str) mylist)
(print mylist)

I want to get a list with two elements like (((a: 3.5) (b: 4.2) (mystring: test)) ((a: 5.6) (b: 7.8) (mystring: hello))).

Re: What's wrong with my code?

Posted: Thu Jul 08, 2010 12:35 pm
by gugamilare
Well, to start, the variables mylist, a, b and str were not declared.
Second, Lisp needs parenthesis. This is wrong:

Code: Select all

setq a 10
This is how you should do:

Code: Select all

(setq a 10)
but that is also wrong because a wasn't declared. You should do that with let:

Code: Select all

(let ((mylist nil)
      (a 3.5)
      (b 4.2))
  ...)

Re: What's wrong with my code?

Posted: Thu Jul 08, 2010 1:07 pm
by joybee
Thanks, Gugamilare!

I did have parenthesis around setq in my test program. I just forgot to add it when I typed the post. Like I said, the code I wrote didn't give me the result that I want. I am trying to learn lisp and I used setq here because later I want to try to read data from a file and assign the data to various variable to create a list. Unfortunately I even failed this simple step. The list I got was like
(a: 3.4) (b: 4.2) (mystring: test) (a: 7.8) (b: 8.9) (mystring: hello) (one element in the list?)
instead of two elements in the list which is what I want.

Re: What's wrong with my code?

Posted: Thu Jul 08, 2010 3:07 pm
by nuntius
Aha! I think I now understand what you want. Try working with the following code.

Code: Select all

(defun arglist (a b str)
  (list (list :a a)
        (list :b b)
        (list :mystring str)))

(let ((mylist nil))
  (push (arglist 3.5 4.2 "test") mylist)
  (push (arglist 5.6 7.8 "hello") mylist)
  (reverse mylist))
There are also built-in functions for lists of key/value pairs (known as association lists, a-list) and for lists that alternate as "(key1 value1 key2 value2 ...)" (known as property lists, p-list). For example, ARGLIST above may be rewritten to return an alist as

Code: Select all

(defun arglist (a b str)
  (pairlis '(:a :b :mystring)
           (list a b str)))

Re: What's wrong with my code?

Posted: Fri Jul 09, 2010 2:17 pm
by joybee
Hi! Nuntius,

It works! Your code's magical!

I don't know how long will it take for me to get basic understanding of lisp. My thinking wasn't even close.

Thanks! :D