Passing functions as parameters



On 2012-07-06, Barton Willis <willisb at unk.edu> wrote:

> The apply method has problems too:
>
>   (%i12) testfun(f, a) := apply(f,[a]) $
>   (%i13) testfun(a,1);
>    apply: found a evaluates to 1 where a function was expected.

Or enclose testfun in a lexical block -- 

blex ([f, a], testfun (f, a) := f (a));

f (x) := 1 + x;
g (x) := 1 - x;
testfun (g, 1);
 => 0
testfun (a, 1);
 => a(1)

I am inclined to give variables lexical rather than dynamic scope in
general. I suspect changing the scope policy wouldn't affect much user
code, and it would prevent a lot of annoying problems.

FWIW

Robert Dodier

PS. a simplistic lexical block implementation. I wouldn't be surprised
if there were a better way to do it.

(defmspec $blex (x)
 (let*
   ((args (cdr x))
    (vars (cdr (car args)))
    (exprs (cdr args))
    (gensym-vars (mapcar #'(lambda (s) (let ((s1 (gensym))) (setf (get
s1 'reversealias) (or (get s 'reversealias) s)) s1)) vars))
    (subst-eqns (mapcar #'(lambda (x y) `((mequal) ,x ,y)) vars
gensym-vars))
    (gensym-mprogn ($psubstitute `((mlist) , at subst-eqns) `((mprogn)
, at exprs))))
   (meval gensym-mprogn)))