Hey,
I am fairly new to Julia and coding. Thus, i still struggle on a lot of things in Julia.
I am trying to solve the exercise 10.1 and would like some help on this, at least where to start.
*Write a function called nestedsum that takes an array of arrays of integers and adds up the elements from all of the nested arrays. For example : * julia> t = [[1, 2], [3], [4, 5, 6]];
Nobody should start Julia with this, for two reasons: 1) It is just using some functions without understanding what they do. 2) It is much slower than a simple implementation using loops:
@rafael.guerra I think the OP is asking for help in approaching a Julia programming problem as a learning exercise. So it’s better if we provide guidance without directly providing the answer.
Just to add to this, recursion and multiple dispatch is a really nice way to handle things like this (though rarely the most performant).
E.g. to demonstrate a related example, lets find the largest element of an arbitrarily nested set of arrays:
julia> mymaximum(iter) = maximum(mymaximum.(iter))
mymaximum (generic function with 1 method)
julia> mymaximum(x::Number) = x
mymaximum (generic function with 2 methods)
julia> mymaximum(t)
8
A more performant approach would probably be to use
mymaximum(iter) = mapreduce(mymaximum, max, iter)
but things like mapreduce tend to take a little time for new users to understand.
Looks like nestedsum is a function that takes no arguments, as in f(). You are calling it as in nestedsum(t), which is throwing an error. If you defined it with t as an input, it would work.
Note that the use of cumsum is not quite correct (I’ll leave that to you to debug). More egregiously though, you are defining sum on the left hand side when the right hand side… uses the sum function. This is obviously very dire, as on iteration 2 you will get the error “objects of type Int64 are not callable”
To expand on the previous poster’s comment, if you can build it with lower-level loops code, then you have the tools to build anything from first principles. Later you can make the code more concise with everything else mentioned above.
The concise options are important to learn but, in this particular case, if one actually faces that problem in real life in a performance-critical code, one should write our own function with loops anyway. It is the fastest approach possible and, if the vectors are large, amenable to vectorization, parallelization, etc. Therefore, writing the loops is not a simple exercise, in my opinion is even the way that problem should be tackled if actually faced in a real code.
But of course, there are functional approaches that are very efficient, and many of which normally one would not know how to write something better. This is not one of such cases, though. And the possibility of writing our custom functions with great performance is what makes Julia great in relation to scripting languages.