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)

2 Answers 2

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.

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

2 Comments

or even b .|> x->log.(x)
Nice. Julia is really powerfully composable.
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.

Comments

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.