9

If I define some anonymous functions a(x) and b(x) as

a = x -> x^2
b = x -> 2x

it would be helpful for recursive problems to add them together, say over the duration of some loop:

for i=1:5
    a = x -> a(x) + b(x)
end

where the goal would be to have this represented internally each loop iteration as

a = x -> x^2 + 2x
a = x -> x^2 + 2x + x^2 + 2x
a = x -> x^2 + 2x + x^2 + 2x + x^2 + 2x
...

But, this fails and returns some error. I'm assuming it's because calling the new a(x) is interpreted as: a(2) = 2 -> x^2 + x^2 + ... + x^2 + 2x

julia> a(2)
ERROR: StackOverflowError:
 in (::##35#36)(::Int64) at ./REPL[115]:0
 in (::##35#36)(::Int64) at ./REPL[115]:1 (repeats 26666 times)

Is there any way around this?

4
  • I don't know Julia, but a = x -> a(x) + b(x) looks like a recursive definition. Can't you just name it something else? c = x -> a(x) + b(x) Commented Jun 14, 2017 at 16:56
  • And I think it's kind of confusing the issue to say that you're trying to add functions together. Really, you're trying to add the return values of the functions together. Commented Jun 14, 2017 at 16:57
  • While that does work, it doesn't for my particular case. I need a commutative solution for stringing together actual representations of x's instead of function calls to a(x) and b(x), which becomes infinitely recursive and generates the error. Commented Jun 14, 2017 at 17:03
  • It's appropriate you came here for an answer. Commented Jun 14, 2017 at 23:59

3 Answers 3

9

You can do exactly what you're looking for using the let keyword:

a = x -> x^2
b = x -> 2x

for i=1:5
  a = let a = a; x -> a(x) + b(x); end
end

a(2) # returns 24

Explanation

The let keyword allows you to create a block with local scope, and return the last statement in the block back to its caller scope. (contrast that with the begin keyword for instance, which does not introduce new scope).

If you pass a sequence of "assignments" to the let keyword, these become variables local to the block (allowing you, therefore, to re-use variable names that already exist in your workspace). The declaration let a = a is perfectly valid and means "create a local variable a which is initialised from the a variable of the outer scope" --- though if we wanted to be really clear, we could have written it like this instead:

for i=1:5
  a = let a_old = a
        x -> a_old(x) + b(x); 
      end
end


then again, if you were willing to use an a_old variable, you could have just done this instead:
for i=1:5; a_old = a; a = x-> a_old(x) + b(x); end


let is a very useful keyword: it's extremely handy for creating on-the-spot closures; in fact, this is exactly what we did here: we have returned a closure, where the "local variable a" essentially became a closed variable.


PS. Since matlab was mentioned, what you're doing when you evaluate a = @ (x) a(x) + b(x) in matlab is essentially creating a closure. In matlab you can inspect all the closed variables (i.e. the 'workspace' of the closure) using the functions command

PPS. The Dr Livingstone, I presume?

Sign up to request clarification or add additional context in comments.

4 Comments

Wow. A use for the let statement? I need more good examples of it, it see it used so little. Possibly it might be clearer to say let a_old=a ?
@LyndonWhite thanks, good point. I edited the post to that effect :) --- having said that, let a = a is kinda the whole point of the let block, otherwise you could have simply done for i=1:5; a_old = a; a = x-> a_old(x) + b(x); end
You sir, are a gentleman and a scholar. Thank you! (PPS. You have no idea how often I hear that joke)
@DanielR.Livingston ahahah, I can imagine! I still have to make it though :p
5

Using Polynomials package could be a way. This would go:

julia> using Polynomials   # install with Pkg.add("Polynomials")

julia> x = Poly([0,1])
Poly(x)

julia> a = x^2
Poly(x^2)

julia> b = 2x
Poly(2*x)

julia> a = a+b
Poly(2*x + x^2)

julia> a(2.0)
8.0

The reason this works is because essentially the behavior you want is symbolic manipulation of functions. Julia does not work this way (it's a compiler - or ahead-of-time (AOT) compiler), but it is flexible. If fancier functions than polynomials are required, maybe a symbolic math package would help (there is SymPy, but I haven't used it).

1 Comment

BTW if using Polynomials is enough, it is faster and less memory hungry than the closure solution which eats up stack and nests calls for every invocation. This is important especially if a is updated in a loop with many iterations.
1

This:

a = x -> a(x) + b(x)

is a recursive call with no stopping condition. It has nothing to do with Julia. As soon as you define this the previous definition (x^2) was overridden, and will have nothing to to with the stack or your result. It doesn't exist anymore. What you're trying to do is:

a(2) = a(2)+2*2 = (a(2)+2*2)+2*2 = ((a(2)+2*2)+2*2)+2*2 = ...

etc. The 2*2 will not even be substituted, I just wrote it to be clear. You probably want to define

c = x -> a(x) + b(x)

EDIT

I see now coming from MATLAB you're expecting the syntax to mean something else. What you wrote in nearly all languages is a recursive call, which you do not want. What you do want is something like:

concatFuncs => f1,f2 -> (x->f1(x)+f2(x))

This piece of code will take any to functions accepting an x and generate a + between the resulting calls. This will work with anything that '+' works with. So:

summed = concatFuncs(a,b)

is the function you need.

6 Comments

Exactly, that's the problem that I'm trying to circumvent. In Matlab, for instance,a = @(x) a(x) + b(x) == a = @(x) x^2 + 2x - the function a(x) and b(x) is hard-coded as what they represent, rather than calls to themselves, before being passed back as a sum to a(x)
@DanielR.Livingston You're comment is cut off, but no matter - this will not work in any language. It literally means what I wrote above. Just define a regular Julia function, with an if statement as a stop condition. Otherwise it's not clear what you actually want - calculating a = x -> a(x) for any x is impossible and meaningless. When do you want the substitution to stop?
I get completely what you are saying - the issue is that function calls are embedded with a = a + b (which generate that recursive death-spiral), as opposed to hard-coded x representations, which is what I want: a = x^2 + 2x
@DanielR.Livingston Define a function called concatFuncs that accepts two functions and returns a new function concatenating them however you want. This will mimick the == behaviour in matlab. Then use it whenever you want to concatenate the functions. You do not want recursion. I will add the matlab syntax you're using while working s un-intuitive and incompatible with all other languages, so watch out when migrating from matlab - it has a lot of 'oddities'.
@kabanus There's nothing 'odd' about matlab. Just different philosophy. This is purely a difference between what it means to be a "handle" vs what it means to be a "function object". A handle that expects a single input and uses values inside it that were not passed explicitly behaves as a closure. That is all.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.