For example, for each element of a vector, I want to calculate the sum of the residuals with other elements of this vector. This works correctly for one element:
a = [1, 2, 5, 7, 8, 22]
f(x) = sum(abs.(x .- a))
f(2)
Out: 35
But if apply this function to all elements using map(), Julia return an error:
map(a, f)
Out: "MethodError: no method matching iterate(::typeof(f))"
In R this is very easy to get using sapply():
a = c(1, 2, 5, 7, 8, 22)
sapply(a, function(x) sum(abs(x - a)))
Out: 39 35 29 29 31 87
Is there an equally elegant way to do this in Julia?
The function map
takes the function that it applies to a collection as its first argument. I.e. you can write
map(f, a)