Re: Newbie-solved a problem in ANSI common lisp
- From: vishy <vishalsodani@xxxxxxxxx>
- Date: Thu, 29 Nov 2007 22:39:34 -0800 (PST)
On Nov 21, 6:09 pm, Rainer Joswig <jos...@xxxxxxx> wrote:
In article
<74ee6ff0-e4a7-4296-8259-5f9e718be...@xxxxxxxxxxxxxxxxxxxxxxxxxxxx>,
vishy <vishalsod...@xxxxxxxxx> wrote:
There is a question in ANSI Common Lisp in Lists chapter-
"Suppose the function pos+ takes a list and returns a list of each
element
plus its position:
(pos+ ' ( 7 5 1 4 ) )(7 6 3 7)
Define this function using (a) recursion, (b) iteration, (c) mapcar."
I have done them in following manner
(a) recursion
(defun ret-add-recur(lst n)(if(and (< n (length lst)) (not nil))
(progn(cons (+ (nth n lst) n) (ret-add-recur lst (+ n 1))))))
(b)iteration
(defun ret-add(lst)(let ((newlst nil))(dolist(obj lst)(push(+ obj
(position obj lst)) newlst))(reverse newlst)))
(c)
(defun ret-add(lst)(mapcar #'(lambda(x)(+ (position x lst) x)) lst))
What do you think of my solutions? How else one could attemt these
problems?
For recursion case,i added extra parameter,the starting position.
regards
vishy
You should really format the Lisp code so that we can read it.
Right now it is just a stream of characters.
A)
Inefficient, needs two args. (NOT NIL) is always T.
B)
Try '(1 1 1) as input. Gives the wrong result.
POSITION is inefficient.
C)
Try '(1 1 1) as input. Gives the wrong result.
POSITION is inefficient.
Generally it is not enough to write the functions.
Write a bunch of test cases with expected outcome
and run the test cases for each function.
For example like this:
(defun run-testcases ()
(let ((functions (list 'ret-add))
(testcases '((((1 1 1)) (1 2 3))
(((2 2 2)) (2 3 4))
(((1)) (1))
(((4 3 2)) (4 4 4)))))
(loop for function in functions collect
(loop for (args result) in testcases
collect (equal (apply function args) result)))))
? (run-testcases)
((NIL NIL T T))
--http://lispm.dyndns.org/
So,are you saying recursion can be written with one argument only-a
list .
thanks
.
- References:
- Newbie-solved a problem in ANSI common lisp
- From: vishy
- Re: Newbie-solved a problem in ANSI common lisp
- From: Rainer Joswig
- Newbie-solved a problem in ANSI common lisp
- Prev by Date: Re: A simple debugging macro
- Next by Date: Re: A simple debugging macro
- Previous by thread: Re: Newbie-solved a problem in ANSI common lisp
- Next by thread: Re: Newbie-solved a problem in ANSI common lisp
- Index(es):
Relevant Pages
|
|