3

Is there a simpler way to do apply a function in Julia to nested array than defining a new function? - e.g. for this simple example:

a = collect(1:10)
b = [ a*i for i in 100:100:400]

arraylog(x) = log.(x) ## Need to define an extra function to do the inner array?
arraylog.(b)
MR_MPI-BGC
  • 265
  • 3
  • 11

2 Answers2

4

I would use a comprehension just like you used it to define b: [log.(x) for x in b].

The benefit of this approach is that such code should be easy to read later.

EDIT

Referring to the answer by Tasos actually a comprehension implicitly defines an anonymous function that is passed to Base.Generator. In this use case a comprehension and map should be largely equivalent.

I assumed that MR_MPI-BGC wanted to avoid defining an anonymous function. If it were allowed one could also use a double broadcast like this:

(x->log.(x)).(b)

which is even shorer but I thought that it would not be very readable in comparison to a comprehension.

Bogumił Kamiński
  • 66,844
  • 3
  • 80
  • 107
1

You could define it as a lambda instead.

Obviously the distinction may be moot, depending on how you're using this later in your code, but if all you want is to not waste a line in your code for the sake of conciseness, you could easily dump this inside a map statement, for instance:

map( x->log.(x),  b )

or, if you prefer do syntax:

map(b) do x
  log.(x)
end

PS. I'm not familiar with a syntax which allows the broadcasted version of a function to be plugged directly into map, but if one exists it would be even cleaner than a lambda here ... but alas 'map( log., b )' is not valid syntax.

Tasos Papastylianou
  • 21,371
  • 2
  • 28
  • 57