Re: Newbie-solved a problem in ANSI common lisp



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
.



Relevant Pages

  • Re: Newbie-solved a problem in ANSI common lisp
    ... vishy wrote: ... Inefficient, needs two args. ... ((NIL NIL T T)) ...
    (comp.lang.lisp)
  • Re: Ugly loop
    ... > NIL ... LOOP may be overestimated. ... * May require one to combine multiple concepts like IF, PROGN, FUNCALL ... * May have recursion problems. ...
    (comp.lang.lisp)
  • Re: Eval recursion with puts.
    ... The usage of "eval" does not initiate any recursion! ... And since puts excepts only one string to be written to a channel you ... % set args; ... set args; ...
    (comp.lang.tcl)
  • Re: Iteration in lisp
    ... demonstrate the point that the recursion is finite and thus ... whether state3 throws to state1 or calls state1. ... 2: (STATE3 NIL) ... 1: returned NIL ...
    (comp.lang.lisp)
  • Remove every atom
    ... I'm still new to Lisp. ... still having lots of difficulties with recursion. ... (defun delete-in (e l) ...
    (comp.lang.lisp)