On Sat, Aug 22, 2015 at 6:34 PM, Tero Frondelius <[email protected]> wrote: > Can you show how to use the Ref in practice, this is merely for academic > purposes, because I had to use the list style anyways for further use of my > code? > > For your questions: this is no performance critical.
https://github.com/yuyichao/explore/blob/619940132a2d70ef67eb19b26c787bcc0d0a75da/julia/counter/counter.jl > > On Sunday, August 23, 2015 at 1:18:00 AM UTC+3, Yichao Yu wrote: >> >> On Sat, Aug 22, 2015 at 2:49 PM, Tero Frondelius >> <[email protected]> wrote: >> > Why testvariable is not incremented? >> > >> > function incrementvariable(numb) >> > numb += 1 >> > end >> > function testing() >> > global testvariable = 0 >> > for i = 1:3 >> > incrementvariable(Ptr{testvariable}) >> > end >> > println(testvariable) >> > end >> >> `+=` is an assignment and not (necessarily) a mutation. A function >> cannot change the binding of a variable in another scope. >> >> What you can do is to mutate the value/object passed in if it is a >> mutable type. The way you are using below is a good example of that. >> On 0.4 you can use the Ref type instead. (Or simple write you own >> counter type `type Counter count::Int end` and use `counter.count += >> 1` to increment it). >> >> As Sisyphuss points out, if you just need a simple local counter, you >> don't need to write a incrementvariable function for that. >> >> If you only need one, a global variable is probably the best choice. >> If you are worrying about performance, a mutable const global (either >> an length-1 array or a Ref or custom counter type) should do it. >> >> If you want a local counter that is shared between different functions >> (by passing as argument), the way you have below (or a modified >> version as mentioned above) is probably the best way. >> >> > >> > Or actually what should I change to get the testvariable incremented? >> > I'm >> > counting how many times one case inside the function incrementvariable >> > is >> > called. I will use this information later in the testing() function. >> > >> > This will work, but it doesn't look elegant: >> > function incrementvariable(numb) >> > numb[1] += 1 >> > end >> > function testing() >> > testvariable = [0] >> > for i = 1:3 >> > incrementvariable(testvariable) >> > end >> > println(testvariable) >> > end >> > >> > >> >
