What's the right way to have local variables in conditional statements within a function? Through trial and error I've found three ways of doing things that (I think) are equivalent in terms of their outcome, although one creates a warning message. I'm curious what other people do and if there are any conventions. I know the distinction is a bit silly, but I don't know if there are any functional differences between the approaches and I'm also curious about what's going on under the hood.
Say I have a function which has a local parameter depending on the input value, something like the following:
```warningMessage = i -> (
if i == 1 then (
v := 2;
return v*i
)
else (
v := 3;
return v*i
)
)
```
This causes the message "warning: local declaration of v shields variable with the same name" to be generated at the line v:=3. This is because when the code is interpreted, the interpreter initializes v as a local variable when it encounters the first instance of v := 2, and then perceives v := 3 as a second initialization of v as a local variable within the same scope. In other words, for the function
```warningMessageSupressed = i -> (
if i == 1 then (
x := 2;
return x*i
)
else (
x = 3;
return x*i
)
)
```
no warning is generated, and x is not assigned a value accessible outside of the function's scope, even if I only call warningMessageSupressed(2). Furthermore, the code
```nullValue = i -> (
if i == 1 then (
y := 2;
return y*i
)
else (
return y*i
)
)
```
returns the error "no method for binary operator * applied to null and ZZ" instead of "...applied to a symbol and ZZ" indicating that y has been initialized as a local variable, even though it hasn't been assigned a value.
Another way to eliminate this message is something like the following:
```
initializeLocal = i -> (
w := w;
if i == 1 then (
w = 2;
return w*i
)
else (
w = 3;
return w*i
)
)
```
To me, this is better than the syntax in warningMessageSupressed, since it is clear that w is local to the function, regardless of which conditional evaluates as true. However, the doc page on ":=" discusses this type of construction only in the context of local symbols for, e.g., creating polynomial rings local to the function, so I don't know if this syntax is considered messy/undesireable as compared to e.g. the syntax I used in the function warningMessageSupressed above.
It's not clear to me that this warning message should be generated in this circumstance. If it is, it might be a good idea for this situation to be addressed in the documentation for the ":=" operator.