Joe Slater on Fri, 13 Sep 2024 00:56:24 +0200


[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]

Re: How can I keep these values local to my function?


That works as far as confining the scope, but I was hoping to have a solution which would allow me to define the variables at run time, rather than having them hard coded. I'm surprised that there's apparently no way to confine the effect of eval() to a local scope. If my variables have to be hard coded anyway, I'll probably use something like my([var1, var2, var3]=binary((options+8)%8). 

Joe Slater

On Wed, 11 Sept 2024 at 16:11, Karim Belabas <Karim.Belabas@math.u-bordeaux.fr> wrote:
Hi,

  just add my(One, Two, Three, Four, Five, Six) to the body of f.
Those will be lexically scoped to f.

Cheers,

      K.B.

* Joe Slater [2024-09-11 03:15]:
> I want to be able to specify binary combinations of options the way that,
> e.g., vecsort() does. I couldn't see a way to do that so I created a
> function, makeoptions(), that returns a vector in the form
> ["a=1","b=2",...] and I use eval() on that vector to create those variables
> within my function. My problem is that eval() creates them with global
> scope, and I can't see a way to make them local.
>
> /* Takes a string containing a list of option names and a number whose
> binary digits represents those options. Returns variables set accordingly.
> */
> makeoptions(s="",options=0)=
> {
>     if(s=="",return());
>     my(v=strsplit(s," "));
>     return(vector(#v,i,(Str(v[i],"=",bitand(2^(i-1),options)<>0))))
> }
> /* A function that uses makeoptions() */
> f(n)={
>     my(a=eval(makeoptions("One Two Three", n)));
>     my(b=eval(makeoptions("Four Five Six", n+1)));
>     print("a=",One,Two,Three);
>     print("b=",Four,Five,Six);
>     }
>
> Here's the output from my function:
> (10:31) > f(2)
> a=010
> b=110
> (10:31) > One \\ Should be undefined
> %2 = 0
> (10:32) > Four \\ Should be undefined
> %3 = 1
> Is there a way to make these variables local, or another way to achieve
> what I want: local named variables set at run time without having a routine
> along the lines of Opt1=bitand(options,1); Opt2=bitand(options,2); ...
>
> Thanks,
> Joe Slater
--
Pr. Karim Belabas, U. Bordeaux, Vice-président en charge du Numérique
Institut de Mathématiques de Bordeaux UMR 5251 - (+33) 05 40 00 29 77
http://www.math.u-bordeaux.fr/~kbelabas/