Anonymous function as argument

Why is common practice to use anonymous funtions where a normal function could be used instead? I’m specilly thinking when using it as an argument of another function. For example:

plot(0:0.1:2π, x -> sin(x))

I’ve seen code like that a lot but I don’t know why since

plot(0:0.1:2π, sin)

works perfectly fine.

I haven’t seen that. Can you link to an example?

1 Like

Basically is the same as my MWE but here is this example from a Chaos course:

function analisis_grafico(f, x0::Float64, n::Int, domx=0.0:1/128:1.0)
    #Graficamos x->F(x) y x->x
    Plt1 = plot(domx, x->f(x),
        xaxis=("x", (domx[1], domx[end])),
        yaxis=("f(x)"),
        color=:blue, legend=false, grid=false)

    plot!(Plt1,
        domx, identity, color=:blue, linestyle=:dash)

    #Se grafican los iterados
    analisis_grafico!(Plt1, f, x0, n, domx)
    return Plt1
end

I’ve seen this in other contexts but I don’t remember them right now.

I’d guess they just weren’t thinking about it.

Yeah, there’s no particular reason to do that, and it’s certainly not necessary. I’d guess that you might occasionally see it in a context where someone is trying to show more generally how an anonymous function /could/ be used, and they’ve just unintentionally chosen an example that could also be written without one.

1 Like

In that particular case that is not needed, but if they wanted to use an additional parameter for the function they could have done something like:

f(x,a) = a*x
function analisis_grafico(f, x0::Float64, n::Int, domx=0.0:1/128:1.0)
    a = 5.0
    Plt1 = plot(domx, x->f(x,a),
...

because the plot function is expecting a function with one variable, but you want to pass to it a function with two, one being a fixed parameter.

7 Likes

I have used something similar when the function f takes keyword arguments that I want to move away from the default values.

:thinking:

Yeah, I was also thinking that it would be necesary in the following example:

plot(0:0.1:2π, x -> sin(x^2))

Do you have an example?

function f(x; exponent=2)
    sin(x^exponent)
end

plot(0:0.1:2π, x -> f(x; exponent=3))
1 Like

Got it, thanks. (:

Thank you all for your replies. In the example I gave, there is no need to use an anonymous function but it is necessary to reduce the number of arguments of a function.

1 Like