# Think Julia Exercise 10.1

**URL:** <https://discourse.julialang.org/t/think-julia-exercise-10-1/50098>\
**Category:** General Usage\
**Created:** [November 13, 2020, 3:59pm UTC](https://discourse.julialang.org/t/think-julia-exercise-10-1/50098 "2020-11-13T15:59:30Z")\
**Posts on this page:** 17\
**Page:** 2

<div class="post-metadata">

**Author:** ![AKL](https://avatars.discourse-cdn.com/v4/letter/a/ba9def/32.png) [@AKL](https://discourse.julialang.org/u/AKL)\
**Post date:** [November 14, 2020, 11:20am UTC](https://discourse.julialang.org/t/think-julia-exercise-10-1/50098/22 "2020-11-14T11:20:36Z")

</div>

Hey,

i think i made some progress and i am close to finding it.  
This is what i have for now :

> function nestedsum(t)  
> total = 0  
> for i = 1:length(t)  
> x1=0  
> for j = 1:length(t[i])  
> x1 = x1 .+ t[i]
> 
> ```
> end
> 
> total = total .+ x1
> 
> ```
> 
> end  
> end  
> nestedsum(t)

now, for the last part, I got DimensionMismatch(“arrays could not be broadcast to a common size; got a dimension with lengths 2 and 3”) and truthfully, I don’t know how to get over it…

Thank you all for your help

---

<div class="post-metadata">

**Author:** ![anon92994695](https://avatars.discourse-cdn.com/v4/letter/a/ce7236/32.png) [@anon92994695](https://discourse.julialang.org/u/anon92994695)\
**Post date:** [November 14, 2020, 11:32am UTC](https://discourse.julialang.org/t/think-julia-exercise-10-1/50098/23 "2020-11-14T11:32:08Z")

</div>

Nice effort AKL.  
I think the problem with your code is your use of the broadcast operator.

`+` and `.+` are different things.  
Try the following:

```julia
a = 2
b = 3
c = a + b
println(c)

```

Now try this

```julia
a = [1,2,3]
b = [3,4,5]
c = a .+ b
println(c)

```

There’s also an indexing bug. Your code should look like this:

```nohighlight
function nestedsum(t)
    total = 0
    for i = 1:length(t)
        x1 = 0
        for j = 1:length(t[i])
            #t[i] will get the list inside the list of lists
            #t[i][j] will get the item inside the list inside the list of lists
            x1 = x1 + t[i][j]
        end
        total = total + x1
    end 
    return total
end

```

But what if we told you you could iterate over your collections like the following:

```nohighlight
for i in t
        x1 = 0
        for j in i
            ...
        end
        ...
    end 

```

How might your code look then?

---

<div class="post-metadata">

**Author:** ![tomerarnon](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tomerarnon/32/3170_2.png) [@tomerarnon](https://discourse.julialang.org/u/tomerarnon)\
**Post date:** [November 14, 2020, 11:32am UTC](https://discourse.julialang.org/t/think-julia-exercise-10-1/50098/24 "2020-11-14T11:32:42Z")

</div>

`.+` is broadcasted `+`. Since you should be adding only scalars in this problem, you shouldn’t need to use it. The reason you found you _did_ need it is on this line:

```julia
x1 = x1 .+ t[i]

```

Consider: what is `t[i]`?

---

<div class="post-metadata">

**Author:** ![AKL](https://avatars.discourse-cdn.com/v4/letter/a/ba9def/32.png) [@AKL](https://discourse.julialang.org/u/AKL)\
**Post date:** [November 14, 2020, 11:36am UTC](https://discourse.julialang.org/t/think-julia-exercise-10-1/50098/25 "2020-11-14T11:36:48Z")

</div>

you’re right, i took out the broadcast and succeeded !

> function nestedsum(t)  
> total = 0  
> for i = 1:length(t)  
> x1=0  
> for j = 1:length(t[i])  
> x1 = x1 + t[i][j]  
> end  
> total = total + x1  
> end  
> println(total)  
> end

---

<div class="post-metadata">

**Author:** ![anon92994695](https://avatars.discourse-cdn.com/v4/letter/a/ce7236/32.png) [@anon92994695](https://discourse.julialang.org/u/anon92994695)\
**Post date:** [November 14, 2020, 11:39am UTC](https://discourse.julialang.org/t/think-julia-exercise-10-1/50098/26 "2020-11-14T11:39:43Z")

</div>

Great AKL.

Now let’s do the Julia thing and see if we can make your code simpler, and learn some things in the process.

Do you see any redundancies in your code? For example, do we need to tally the sum of each inner loop in a seperate variable? Or could we just use one variable to count the entire sum(`total`)?

---

<div class="post-metadata">

**Author:** ![AKL](https://avatars.discourse-cdn.com/v4/letter/a/ba9def/32.png) [@AKL](https://discourse.julialang.org/u/AKL)\
**Post date:** [November 14, 2020, 11:44am UTC](https://discourse.julialang.org/t/think-julia-exercise-10-1/50098/27 "2020-11-14T11:44:35Z")

</div>

yes i am now working on what you told me with i in j  
i’ll post what i have when it works 😅

---

<div class="post-metadata">

**Author:** ![anon92994695](https://avatars.discourse-cdn.com/v4/letter/a/ce7236/32.png) [@anon92994695](https://discourse.julialang.org/u/anon92994695)\
**Post date:** [November 14, 2020, 11:48am UTC](https://discourse.julialang.org/t/think-julia-exercise-10-1/50098/28 "2020-11-14T11:48:45Z")

</div>

It doesn’t have to work to be posted :). But your best effort and a description of what you tried is perfectly acceptable. You’re learning something new - perfection isn’t expected. No rush either.

10.1 is a great example to show some of the ways julia lets you handle things. So I’m more than willing to walk you through a bit more. Point isn’t for you to remember everything, but just remember there are alternatives and kind of guide you along a new way of thinking.

---

<div class="post-metadata">

**Author:** ![AKL](https://avatars.discourse-cdn.com/v4/letter/a/ba9def/32.png) [@AKL](https://discourse.julialang.org/u/AKL)\
**Post date:** [November 14, 2020, 12:14pm UTC](https://discourse.julialang.org/t/think-julia-exercise-10-1/50098/29 "2020-11-14T12:14:35Z")

</div>

You are telling me to use only one variable(total) to compil the code

so 😅

```julia
function nestedsum1(t)
for i in t
        x1 = 0
        for j in i
            x1 = x1 + t[i][j] #here, I don't understand I how I can replace the [i][j]
        end
        x1 #here, if i have only variable, should i simply say that x1 = x1+i?
    end 
	println(x1)
end

```

---

<div class="post-metadata">

**Author:** ![anon92994695](https://avatars.discourse-cdn.com/v4/letter/a/ce7236/32.png) [@anon92994695](https://discourse.julialang.org/u/anon92994695)\
**Post date:** [November 14, 2020, 12:21pm UTC](https://discourse.julialang.org/t/think-julia-exercise-10-1/50098/30 "2020-11-14T12:21:33Z")

</div>

Close,  
Look at what you are doing in the first loop. You are resetting this value to 0 at each iteration.

Does this will help

```nohighlight
function nestedsum1(t)
    total = 0.0
    for i in t
        #i is now a list in t
        for j in i
            #j is now an item in i (remember i is a list in t)
            total = total + j  
        end
    end 
    println(total)
end

```

---

<div class="post-metadata">

**Author:** ![AKL](https://avatars.discourse-cdn.com/v4/letter/a/ba9def/32.png) [@AKL](https://discourse.julialang.org/u/AKL)\
**Post date:** [November 14, 2020, 12:35pm UTC](https://discourse.julialang.org/t/think-julia-exercise-10-1/50098/31 "2020-11-14T12:35:02Z")

</div>

oh !  
I think i understood a bit better how this works !

Thank you !

---

<div class="post-metadata">

**Author:** ![anon92994695](https://avatars.discourse-cdn.com/v4/letter/a/ce7236/32.png) [@anon92994695](https://discourse.julialang.org/u/anon92994695)\
**Post date:** [November 14, 2020, 12:43pm UTC](https://discourse.julialang.org/t/think-julia-exercise-10-1/50098/32 "2020-11-14T12:43:43Z")

</div>

No problemo.

So basically we can iterate over collections/iterables like lists/arrays/etc using `in`. This will do what we expect - read each collection from the first element to the last element.

The way you originally wrote the code used the indices to iterate over your collections.

Both of these choices are mostly identical but appear a little different in code. One is easier to read, and maybe will reduce human errors, but, a programmer could prefer one or the other based on what they are comfortable with :).

Here’s another fun thing, in Julia we can rewrite nested loops like the following,

```nohighlight
function nestedsum1(t)
    total = 0.0
    for i in t, j in i
        total = total + j  
    end 
    println(total)
end

```

Again, this is the same as above but, it’s nice and concise. Maybe a programmer wouldn’t want to do this because it’s a little muddled to read, but very neat.

Again, you don’t have to do any of this, but, knowing your way around loops, broadcasting, etc will help you read other peoples code :).

going further we can introduce another operator

```julia
total += j

```

this is equivalent too `total = total + j`. but looks neat and saves our fingers some extra work.

---

<div class="post-metadata">

**Author:** ![stevengj](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevengj/32/71_2.png) [@stevengj](https://discourse.julialang.org/u/stevengj)\
**Post date:** [November 14, 2020, 12:55pm UTC](https://discourse.julialang.org/t/think-julia-exercise-10-1/50098/33 "2020-11-14T12:55:46Z")

</div>

I totally agree that it is good to learn to write this using low-level constructs like loops, even though `sum(sum, a)` is efficient and concise.

One tricky part about explicit loops is making them type-generic—if you are writing flexible libraries, experienced Julia programmers work hard to make the code composable with arbitrary user-defined types…

If you want a loop to work for summing _anything_ efficiently (e.g. complex numbers, matrices, different precisions, unitful values…), then you should initialize your sum to `zero(eltype(eltype(a)))` instead of `0` or `0.0`. (Or better yet, initialize the sum using the type of the first element, in the case of non-empty arrays; this is what `sum` does if it can in order to handle abstractly typed containers.)

On the other hand, this is not something I would worry about for your first steps in learning Julia. Not all code needs to be generic (or fast)!

---

<div class="post-metadata">

**Author:** ![anon92994695](https://avatars.discourse-cdn.com/v4/letter/a/ce7236/32.png) [@anon92994695](https://discourse.julialang.org/u/anon92994695)\
**Post date:** [November 14, 2020, 1:11pm UTC](https://discourse.julialang.org/t/think-julia-exercise-10-1/50098/34 "2020-11-14T13:11:49Z")

</div>

This may be an aside/seperate thread but I wonder what order of priority is most effective for pedagogy.

Off the top of my head I am seeing it something like the following

1. Declaration/Instantiation
2. Inspection/Printing/basic I/O
3. Control Structure
4. Types/Objects/Classes/Instances
5. Loading/Importing/etc
6. Recursion
7. Algorithms
8. Performance

Something like that anyway…

---

<div class="post-metadata">

**Author:** ![Tamas\_Papp](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tamas_papp/32/25949_2.png) [@Tamas\_Papp](https://discourse.julialang.org/u/Tamas_Papp)\
**Post date:** [November 14, 2020, 1:27pm UTC](https://discourse.julialang.org/t/think-julia-exercise-10-1/50098/35 "2020-11-14T13:27:51Z")

</div>

> [@stevengj](#):
>
> If you want a loop to work for summing _anything_ efficiently (e.g. complex numbers, matrices, different precisions, unitful values…), then you should initialize your sum to `zero(eltype(eltype(a)))` instead of `0` or `0.0` .

Unfortunately, that will not work when said `eltype` is `Any` or something else for which `zero` is not defined.

---

<div class="post-metadata">

**Author:** ![stevengj](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevengj/32/71_2.png) [@stevengj](https://discourse.julialang.org/u/stevengj)\
**Post date:** [November 14, 2020, 1:57pm UTC](https://discourse.julialang.org/t/think-julia-exercise-10-1/50098/36 "2020-11-14T13:57:44Z")

</div>

> [@Tamas\_Papp](#):
>
> Unfortunately, that will not work when said `eltype` is `Any` or something else for which `zero` is not defined.

Yes, that’s why I said it is even better to use the first element, _if_ the array is non-empty, to initialize the sum. That’s what `sum` does. If the container is abstractly typed _and_ empty, then the only thing we can currently do is throw an error:

```julia
julia> sum(Any[])
ERROR: MethodError: no method matching zero(::Type{Any})

```

In Julia 1.6 there is an `init` keyword to specify the accumulation starting point/type ([https://github.com/JuliaLang/julia/pull/36188](https://github.com/JuliaLang/julia/pull/36188)). Generic programming is tricky (but rewarding!).

(This has long been a source of contention/confusion. See [behavior of sum, prod, mapreduce... on empty arrays · Issue #8092 · JuliaLang/julia · GitHub](https://github.com/JuliaLang/julia/issues/8092), [Mean of an empty collection · Issue #28777 · JuliaLang/julia · GitHub](https://github.com/JuliaLang/julia/issues/28777), [sum(f, itr) when itr is an empty collection should return zero · Issue #36262 · JuliaLang/julia · GitHub](https://github.com/JuliaLang/julia/issues/36262), [Defining zero() seriously · Issue #34003 · JuliaLang/julia · GitHub](https://github.com/JuliaLang/julia/issues/34003), etc.)

---

<div class="post-metadata">

**Author:** ![Tamas\_Papp](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tamas_papp/32/25949_2.png) [@Tamas\_Papp](https://discourse.julialang.org/u/Tamas_Papp)\
**Post date:** [November 14, 2020, 2:12pm UTC](https://discourse.julialang.org/t/think-julia-exercise-10-1/50098/37 "2020-11-14T14:12:14Z")

</div>

> [@stevengj](#):
>
> Generic programming is tricky (but rewarding!)

I think that in this respect, Julia is navigating uncharted territory (unprecedented combination of language featues) but will gradually develop its own solutions. At the moment replicating what language built-ins like `collect` are doing is tricky, but approaches like

> **[JuliaFolds](https://github.com/JuliaFolds)**
>
> JuliaFolds hosts Julia packages for sequential and parallel fold (aka reduce) algorithms - JuliaFolds

are very promising.

---

<div class="post-metadata">

**Author:** ![Vasily\_Pisarev](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/vasily_pisarev/32/7929_2.png) [@Vasily\_Pisarev](https://discourse.julialang.org/u/Vasily_Pisarev)\
**Post date:** [November 14, 2020, 2:39pm UTC](https://discourse.julialang.org/t/think-julia-exercise-10-1/50098/38 "2020-11-14T14:39:19Z")

</div>

As Chapter 10 has a subsection about `map`, `filter` and `reduce`, the most “logical” solution in context is trying to use those.

It is easy to see that sum of `a` if `a` is an array of `Int`s is `reduce(a, +)` (or `sum(a)`, as shown in the same subsection).

Sum of `aoa` where `aoa` is an array of arrays is just sum of all sums of inner arrays, i.e. `sum(map(sum, aoa))`.

So,

```julia
julia> nestedsum(aoa) = sum(map(sum, aoa))
nestedsum (generic function with 1 method)

julia> t = [[1, 2], [3], [4, 5, 6]];

julia> nestedsum(t)
21

```

With multiple dispatch (which is introduced only in Chapter 17), one can write a function that works with arbitrarily nested arrays:

```julia
julia> nestedsum(a) = sum(map(nestedsum, a))
nestedsum (generic function with 1 method)

julia> nestedsum(x::Number) = x
nestedsum (generic function with 2 methods)

julia> t = [[1, 2], [3], [4, [5, 6]]];

julia> nestedsum(t)
21

```

[Previous page](https://discourse.julialang.org/t/think-julia-exercise-10-1/50098.md?page=1)
