Easier way to sum a list of integers
Hello there, I'm trying to learn Mojo by creating some small simple programs and comparing them to Python to learn key differences. I've joined an example of the last function I wrote in my code.
In this specific case, get_unbiased_run returns an integer value and the goal of this function is to sum the value of all runs. In Python, one would do a simple one liner by summing all elements of a generator. I don't know what the equivalent would be in mojo and believe this code can be optimised. I've noticed the existence of Buffers and the "sum" function from the algorithm module but not sure how I could make it work here. Any help is welcomed !
Thanks in advance π
11 Replies
I do not see aggregate functions in the doc. However, you can do something like this:
map[add](5)
... does this require some kind of import or something? Sorry for noob Q -- while I'm an aspiring Mojician, I still consider myself a Mojician's Assistant.Since the
map
function isn't part of the builtin module, you'll need to explicitly import it: from algorithm import map
Congrats @Jake Brooks, you just advanced to level 1!
ty!
For any other potential readers: https://docs.modular.com/mojo/stdlib/algorithm/functional
Ty again, @Jake Brooks . π
@seboll13 is your goal speed or simplify ease of writing/using code? If it is speed then youll want to look into Parameters, unroll, and SIMD instructions (like reduce_add), if its just ease of use then the above answers are fantastic :)
I have to admit, my brain needs a rewire. I imagine others might feel the same. Generally when I'm programming in Python/JS/shell(don't-judge-me)/other-interp-languages, I think approach problems in a somewhat "hacky" way. But as soon as I'm doing Go/Rust/C/other-compiled-languages, I suddenly approach them from a more optimized vantage. Mojo is really messing with my brain. In a good way.
Congrats @bunny, you just advanced to level 3!
Iβd say a bit of the two but mostly speed. Iβm trying to optimise as best I can in order to see whatβs the fastest execution time I can get.
But thanks for your input π
if you send the full code I can help, but likely SIMD will be the way to go
Iβll understand how it works then and get back to you if needed:)