How to sum up values of a struct?

I have a struct.
s = %S{a: 1, b: 2}

and, a list.
l = [3, 4]

and, I want a fn() to sum up the values of “s” after multiplying each with an element of “l” in order. I hope fn(s, l) returns (1 * 3) + (2 * 4) = 11

What is the shape of fn()?

Thank factoryd for my last question.

Maps are not ordered, so what would be the order for the numbers in %S{}?

3 Likes

I didn’t think of it, map is not ordered. I’ll edit the question.

I need another map rather than a list. If I prepare two maps, then, the problem is solved.

Then you’ll have two datatypes without order, so it’s even less deterministic. Unless you’re matching by key.

1 Like

Actually, I have the same datatypes. So, no problem. Thank you, LostKobrakai

The same problem still happens even if you have two instances of the same struct type. If you have two unordered collections, then you may get different sums every time you call. I said may because it is an implementation detail and it might work for some collections due to how maps/structs are implemented. But you shouldn’t trust it.

Maybe you should share more details of your problem. In general if you want an ordered operation, you need to use ordered data structures, such as lists.

1 Like

I have a feeling that it could be solved with protocols. If you implement the Enumerable protocol to your struct, specifying how it is enumerable. I think it would be possible!

But I’m learning yet, so maybe you want to check it yourself. Just a tip

1 Like