ezaf
...@pioneer-usa.com (Eqbal Z) writes:
> asi
...@math.bme.hu (Simon Andr s) wrote in message <
news:vcdbs3mp1bc.fsf@tarski.math.bme.hu>...
> > ezaf
...@pioneer-usa.com (Eqbal Z) writes:
> > > Hi,
> > > I need to write a lisp function rev(lst revlist) which reverses the
> > > list lst and stores it in revlist.
> > > I am able to write the rev(lst) function but how do I write the
> > > function so the result is stored in one of its arguments?
> > If you're willing to pass a cons as the second argument, then you can
> > (but shouldn't) do this by setf-ing its car and cdr to that of the
> > reversed list. But note that CL is not C, so only do this if it's a
> > homework assignment and you're desperate.
> > Andras
> Yes this is a homework assignment. How do you pass cons as an argument?
Since you want probably recover the modified value after the call, you
need to keep a reference to the cons. So first, you assign it to a
variable (theta in my case) then you call the function passing that
variable 'by value'. Just that a cons contains two pointers, so you
effectively passed a reference to the function. Note that in my case I
only modify the cdr of the cons but both the car and the cdr can be
used.
(defun fun (n output)
(do ((i 0 (1+ i)))
((> i n))
(push i (cdr output))))
(show
(let ((theta (cons nil nil)))
(fun 3 theta)
(cdr theta))
)
==> (3 2 1 0)
Of course, instead of having an 'output' or 'inout' parameter that
needs such a special initialization before calling, you may want to
have a input parameter and recover an output as result, maybe a
multiple result if the function must return other values too.
So, instead of writting:
(setq inout (cons nil variable))
(setq result (fun n inout))
(setq variable (cdr inout))
and using (setf (cdr inout) ...) and (cdr inout) in the function fun,
(defun fun (n inout)
;; ...
(setf (cdr inout) (f (cdr inout)))
;; ...
result)
[ note the equivalence with C:
result=fun(n,&variable);
result_t fun(int n,variable_t* inout)
{
/* ... */
(*inout)=f(*inout);
/* ... */
return(result);
}
]
you may also write:
(multiple-value-bind (res out) (fun n variable)
(setq result res)
(setq variable out))
and use (setq inout) and inout in the function fun and (values result
inout) at the end:
(defun fun (n inout)
;; ...
(setq inout (f inout))
;; ...
(values result inout))
[ note the equivalence with C: oops, you can only return one result here...
variable=fun(n,variable);
variable_t fun(int n,variable_t inout)
{
/* ... */
inout=f(inout);
/* ... */
return(inout);
}
]
--
__Pascal_Bourguignon__ http://www.informatimago.com/
----------------------------------------------------------------------
There is a fault in reality. do not adjust your minds. -- Salman Rushdie