Turn code into function

(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...)
returns 5, but if I add
q = [2,3]

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 )

Possibly, because R has no scalars, only vectors. :wink:

In your example, if you call f with [2,3], then x will be a tuple ([2, 3],), so sum will sum this tuple.

No; also there are no “environments” in the R sense in Julia.

I would recommend that you start from the basics, and work through the Julia manual first. Trying to adapt R concepts to Julia will just be a source of continuous frustration.

Also, please quote your code.


Also you may find this particular section of the docs interesting Noteworthy differences from R.


Thank you!

Thank you! I think I was struggling because it was late at night and nothing made sense. I think I misunderstood an earlier error, tried to fix it, and introduced a new one without realizing it. But thank you for your help!

Also, sorry for the lack of indents and back-ticks. I’m not used to formatting comboxes for code, and tried to use spaces for indents, and didn’t know how to make it look like code (with back-ticks). The best practice recommendations are much appreciated.

1 Like