I want to make this function:
using function composition, I tried this forms, but none works.
(sum ∘ sqrt.)(rand(10))
(sum ∘ sqrt)(rand(10))
(sum .∘ sqrt)(rand(10))
(sum ∘ sqrt)(.rand(10))
How do I do this function composition works?
Close, it’s the one permutation you didn’t try:
julia> (sum ∘ sqrt).(rand(10))
You’re just composing functions not doing element-wise composition of vectors of functions, so you just use
. is part of the call syntax, not the name of the function. You can think of
.( ) as the “vectorized call operator” just like
( ) after an expression is the normal call operator.
That isn’t equivalent to
sum(sqrt.(rand(20))) because it is broadcasting
sum as well. I don’t think that there is a way to achieve this using function composition.
I mean there’s this:
julia> (sum ∘ (v -> sqrt.(v)))(rand(20))
But I’m not sure why you’d want to write that instead of
rand is to be part of it, then the simplest is
sum(x -> sqrt(rand()), 1:20)
rand(20) is a placeholder for another array
sum ∘ (x -> sqrt.(x))
OP probably expected that something like
(sqrt.) could be syntactic sugar to
x -> sqrt.(x)
Is there any reason why it is not?
I believe that this transformation would break broadcast fusion. For example:
a(x) = 2x
b(x) = x/2
x = rand(10000);
@btime a.(b.(x)); # 9.7 μs
@btime a.((x -> b.(x))(x)); # 23.6 μs
(using timing results as a proxy for broadcast fusion…)