Function with "memory"

I want to make a function with “memory”, that only modifies the second argument if the first satisfies certain conditions and otherwise returns the same second argument. Both arguments should be “scalar”/only one scalar value is of interest.

In the solution below b is not modified if 0 <= a <= 1:

function foo(a, b)
if a < 0
    b[1] = 1
elseif a > 1
    b[1] = 0
end
b
end

b = [2]
foo(0.5, b)
foo(1.5, b)
foo(-0.5, b)

However, it seems clumsy to use a vector only to act as a container. Any good suggestions for a better solution?

It’s unclear what exactly do you want. If you just want a condition, you can just return the modified value. Or if you don’t want to use return value, you’ll have to use a mutable input type to get a “output” argument. You can use any mutable types for it including Array, RefValue or any custom types.

I’m not familiar with RefValue and no results turn up when searching in the docs – do you have a reference?

I actually thought that Arrays where the only mutable (non-custom) type…?

Don’t think of “modifying” the argument, just return it:

function foo(a, b)
    if a < 0
        b = 1
    elseif a > 1
        b = 0
    end

    return b
end

a = 1; b = 2
b = foo(a, b)
1 Like

There’s no performance gain with trying to do in-place updating of immutable types. Instead, there’s actually a performance loss. Purely using immutables is fastest, it’s just that in many cases this cannot be done (like in cases with array of arbitrary length).

2 Likes

That’s an excellent point – thanks!