juno
juno

Reputation: 13

Need help understanding lisp function

I have trouble understanding this lisp function

Write a function (using pure recursion technique) which accepts a nested list of numbers and returns the list with negative numbers squared and positive numbers (including 0) incremented by 2. For example,
LISP> (f '(2 (-1 (9)) 4))

result of the function

(4 (1 (11)) 6)

I don't know how to write a function that returns a list like the one above

Upvotes: 0

Views: 94

Answers (2)

Gwang-Jin Kim
Gwang-Jin Kim

Reputation: 10163

I now see this is just the tail-recursive version of @Sylwester's answer.

Squaring negative numbers and adding 2 to positive ones:

(defun procedure (x) (if (< 0 x) (+ 2 x) (* x x)))

By writing a recursive function which

(defun apply-to-every (fun l &optional (acc '()))
  (cond ((null l) (nreverse acc))
        ((atom (car l)) 
         (apply-to-every fun 
                         (cdr l) 
                         (cons (funcall fun (car l)) 
                               acc)))
        (t ;; if not an atom it must be a list
         (apply-to-every fun 
                         (cdr l) 
                         (cons (apply-to-every fun (car l)) 
                               acc)))))

Then apply it:

(apply-to-every #'procedure '(2 (-1 (9)) 4))
;; (4 (1 (11)) 6)

;; or:
(defun f (list) 
  (apply-to-nested-list #'procedure list))

(f '(2 (-1 (9)) 4))
;; (4 (1 (11)) 6)

Upvotes: 0

Sylwester
Sylwester

Reputation: 48775

Split the stuff up. eg.

(defun process (n)
  (if (< n 0)
      ...
      ...))

(process -2) ; ==> 4
(process 4)  ; ==> 6

Then you need to have the function itself to iterate a tree.

(defun process-tree (tree)
  (cond ((numberp tree) (process tree)) ; the processing of value happens here
        ((consp tree) ???)              ; the recursion happens here
        (t tree)))                      ; any values inside the tree not numbers. eg. ()

(process-tree -2)               ; ==> 4
(process-tree 4)                ; ==> 6
(process-tree '())              ; ==> ()
(process-tree 'test)            ; ==> test (out of spec, a feature)
(process-tree '(-2 . 4))        ; ==> (4 . 6)    
(process-tree '(2 (-1 (9)) 4))) ; ==> (4 (1 (11)) 6)

Good luck!

Upvotes: 4

Related Questions