(Edited for code legibility.)
I’m having some trouble transitioning from R to Julia. In R, I don’t have to worry if the argument for the function is a scalar or a vector, but in Julia, I get very different results if I try to evaluate a function at stored vector, or at a string of digits. Additionally, in R, I can turn working code into a function, and expect the function to behave exactly like the code does. But, again, in Julia, I can try to turn working code into a function, and get errors when I attempt to call the function. For instance, in R, I can simply define f as:
f <- function(x){sum(cos(x))}
(More complicated versions of this sort of function shows up a lot in Benchmark functions.) Once I’ve defined the function, I don’t have to worry if x is a vector or a scalar, and, more importantly, the code in the function will run exactly the same inside the function as outside it.
But in Julia, I cannot get the same sort of function to work, and the code behaves very differently when inside the function than when outside it.
For instance:
function f(x...)
sum(x)
end
f(2,3)
returns 5, but if I add
q = [2,3]
f(q)
I just get [2,3] back.
So sum doesn’t work for vectors, only for a “list” of scalars. Worse, sum(q) returns 5, so the code itself doesn’t work the same in the function as outside it. (And if instead of sum(x), I used cos.(x), f(q) would result in an error, but f(2,3) would work as expected, even though cos.(q) works as expected.)
Perhaps this has something to do with how environments work?? I don’t have to worry about environments in R. But then how do I make my function take vector inputs? And how do I turn working code into a function? Conversely, if my function isn’t behaving like I expect it to, how do I run parts of it outside the function environment (??) to debug it? (Or is there a better way to debug it? Maybe by defining new functions with )