How to modify a function the way I need?

Discussion of Common Lisp

How to modify a function the way I need?

Postby Lispoman » Sat Aug 22, 2009 5:45 am

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
Lispoman
 
Posts: 12
Joined: Mon Jun 01, 2009 6:09 pm

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

Postby Paul Donnelly » Sat Aug 22, 2009 10:31 am

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.
Paul Donnelly
 
Posts: 148
Joined: Wed Jul 30, 2008 11:26 pm

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

Postby smithzv » Sat Aug 22, 2009 10:44 am

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
smithzv
 
Posts: 94
Joined: Wed Jul 23, 2008 11:36 am


Return to Common Lisp

Who is online

Users browsing this forum: Google [Bot] and 3 guests

cron