Writing the Foo Function In LISP With the following Specification -


i struggling find right approach solve following function

(foo #'– '(1 2 3 4 5)) => ((–1 2 3 4 5) (1 –2 3 4 5) (1 2 –3 4 5) (1 2 3 –4 5) (1 2 3 4 –5))  

the first parameter foo function supposed function "-" has applied each element returning list of list shown above. not sure approach can take create function. thought of recursion not sure how preserve list in each call , kind of base criteria have. appreciated. cannot use loops functional programming.

the base case of recursion can determined asking "when want stop?".

as example, when want compute sum of integer , positive integers below it, can recusively base case determined answering "when want stop?" "when value might add in zero.":

(defun sumdown (val)   (if (zerop val)       0       (+ (sumdown (1- val)) val))) 

with regard 'preserve list in each call', rather trying preserve build result go along. using 'sumdown' example, can done in various ways fundamentally same approach.

the approach have auxiliary function result argument lets build result recurse, , function intended user call, calls auxiliary function:

(defun sumdown1-aux (val result)   (if (zerop val)       result       (sumdown1-aux (1- val) (+ val result))))  (defun sumdown1 (val)   (sumdown1-aux val 0)) 

you can combine auxiliary function , function intended called user using optional arguments:

(defun sumdown2 (val &optional (result 0))   (if (zerop val)       result       (sumdown2 (1- val) (+ val result)))) 

you can hide fact auxiliary function being used locally binding within function user call:

(defun sumdown3 (val)   (labels ((sumdown3-aux (val result)              (if (zerop val)                  result                  (sumdown3-aux (1- val) (+ val result)))))     (sumdown3-aux val 0))) 

a recursive solution problem can implemented answering question "when want stop when want operate on every element of list?" determine base case, , building result list-of-lists (instead of adding in example) recurse. breaking problem smaller pieces - "make copy of original list nth element replaced result of calling function on element" can considered subproblem, might want write function first, use function write function solves whole problem. easier if allowed use functions mapcar , substitute or substitute-if, if not, can write equivalents out of allowed use.


Comments