Page 1 of 1

How to modify a function the way I need?

Posted: Sat Aug 22, 2009 5:45 am
by Lispoman
Hi all. I have a function which places @ symbol before every negative or evenp element of a list. It look's like this

This is an example for even elements.

Code: Select all

(defun mufunc (x)
(cond ((null x) nil)
((evenp (car x)) (cons (intern (format nil "@~a" (car x))) 
(mufunc (cdr x))))
(T (cons (car x) (mufunc (cdr x))))))
This works fine! but I need a to modify it to make possible calls like this

mufunc((LAMBDA (x) (>= x 0)) ‘(1 0 -2 3 0 -4 5)) –> (@ 1 0 -2 @ 3 0 -4 @ 5) - this call for negative elements and it should use lambda and

mufunc(‘EVENP ‘(1 0 -2 3 0 -4 5)) –> (1 @ 0 @ -2 3 @ 0 @ -4 5) - and this for even elements.

I need your help. Help me please

Re: How to modify a function the way I need?

Posted: Sat Aug 22, 2009 10:31 am
by Paul Donnelly
Transforming it into valid Lisp code is a good start:

Code: Select all

(mufunc (LAMBDA (x) (>= x 0)) ‘(1 0 -2 3 0 -4 5)) –> (@ 1 0 -2 @ 3 0 -4 @ 5)
(mufunc #‘EVENP ‘(1 0 -2 3 0 -4 5)) –> (1 @ 0 @ -2 3 @ 0 @ -4 5)
Other than that, it's simple enough. Just add a parameter for the test function and funcall it where you're calling evenp.

Re: How to modify a function the way I need?

Posted: Sat Aug 22, 2009 10:44 am
by smithzv
Lispoman wrote:This works fine! but I need a to modify it to make possible calls like this
Does it?

Code: Select all

CL-USER> (defun mufunc (x)
             (cond ((null x) nil)
                   ((evenp (car x)) (cons (intern (format nil "@~a" (car x)))
                                          (mufunc (cdr x))))
                   (T (cons (car x) (mufunc (cdr x))))))
MUFUNC
CL-USER> (mufunc '(1 2 3 4 5 6 7 8))
(1 @2 3 @4 5 @6 7 @8)
I would expect:

Code: Select all

CL-USER> (defun mufunc2 (x)
             (cond ((null x) nil)
                   ((evenp (car x)) (append (list '@ (car x))
                                            (mufunc2 (cdr x)) ))
                   (T (cons (car x) (mufunc2 (cdr x))))))
MUFUNC2
CL-USER> (mufunc2 '(1 2 3 4 5 6 7 8))
(1 @ 2 3 @ 4 5 @ 6 7 @ 8)
The important part for you (since you want to generalize this to an arbitrary predicate) is:

Code: Select all

                   ((evenp (car x)) (append (list '@ (car x))
                                            (mufunc2 (cdr x)) ))
So, EVENP is your predicate here. You want to replace it with the specified lambda expression. Remember that in Common Lisp, functions that are named by symbols need to be called via FUNCALL (see the HyperSpec for more on this).

Zach