On Mon, Jul 27, 2015 at 3:36 PM,  <[email protected]> wrote:
> Hi all,
>
> I'm a bit confused about how the modification of arguments in Julia works.
> I have a (rather huge) code involving this function:
>
> function next_prediction!(f, g, t, x, u, p)
>     y = system_observation()
>     x = f(t, x, u, p)
>     for o in g
>         obs = observation()
>         o.f(t, x, p, obs)
>         y.set(obs)
>     end
>     return y
> end
>
> This function should both return y and modify x. The problem is that it
> modifies x only inside the function, but when I'm out of next_prediction!, x
> is the same as before the function call.
> So I created a very short test supposed to mimic the behaviour of
> next_prediction!:
>
> type state
>     x
>     y
> end
>
> s = state(1.0,2.0)
>
> function modify_state!(s)
>     s.x = 7.0
>     return 3.0
> end
>
> println(s)
> n = modify_state!(s)
> println(s)
>
> and in that case, the function modify_state! both return 3.0 *and* modify
> the state s. How could we explain the fact that in such a basic example,
> everything works as I want, but not in the more complex code?

In julia, arguments are passed by reference and assignement works by
changing the binding.

This means that if you **mutate** the internal state of a argument
(e.g. `s.x = 7.0`), this change would be visible to the caller (who
passed in `s` as a parameter).

However, when you have `x = 7.0`, this changes the binding of `x` to
`7.0` and this change of binding is local to the function and is not
visible outside the current scope.

>
> Thanks a lot!

Reply via email to