You have problems, and we're glad to hear them. Explain the problem, what you have tried, and where you got stuck.
Feel free to share a little info on yourself and the course.
Forum rules
Please respect your teacher's guidelines. Homework is a learning tool. If we just post answers, we aren't actually helping. When you post questions, be sure to show what you have tried or what you don't understand.
by andrewcmunroe » Fri Nov 09, 2018 10:12 am
Hi. Can I please get some help?
"Write a function MIDADD1 that adds 1 to the middle element of a
threeelement list.
For example, (MIDADD1 ’(TAKE 2
COOKIES)) should return the list (TAKE 3 COOKIES). Note: You
are not allowed to make MIDADD1 a function of three inputs. It
has to take a single input that is a list of three elements."
Here's what I came up with:
(defun midadd1 (l) (+ 1 (car (cdr l))))
This only returns the modified element. How can I get the modified list?

andrewcmunroe

 Posts: 1
 Joined: Fri Nov 09, 2018 9:54 am
by nuntius » Sat Nov 10, 2018 3:21 pm
Construct a new list. Include the original head, new middle, and original tail.
There are ways to destructively modify the middle value in the original list (setf ...), but I think the new list is what your instructor is looking for.
If done right, the amount of code is about the same either way.

nuntius

 Posts: 538
 Joined: Sat Aug 09, 2008 10:44 am
 Location: Newton, MA
by sylwester » Sun Nov 11, 2018 7:20 am
The clearest would be to
 Code: Select all
(defun midadd1 (list)
"Adds 1 to the middle element of a
threeelement list."
(assert (and (listp list) (= (length list) 3)) (list) "~a must be a 3 element list" list)
(destructuringbind (firstelement midnum thirdelement) list
(assert (numberp midnum) (list midnum) "The second element of ~a must be a number. Got ~a" list midnum)
(list firstelement (1+ midnum) thirdelement)))
Of course you can just use accessors:
 Code: Select all
(defun midadd1 (list)
"Adds 1 to the middle element of a
threeelement list."
(assert (and (listp list)
(= (length list) 3)
(numberp (second list))) (list) "~a must be a 3 element list with the second element being numeric" list)
(list (first list) (1+ (second list)) (third list)))

sylwester

 Posts: 132
 Joined: Mon Jul 11, 2011 2:53 pm
Return to Homework
Who is online
Users browsing this forum: No registered users and 1 guest