M
Modularβ€’8mo ago
seboll13

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 πŸ™‚
No description
11 Replies
Grandimam
Grandimamβ€’8mo ago
I do not see aggregate functions in the doc. However, you can do something like this:
fn main():
var c: Int = 0
fn add(a: Int, /) capturing:
c += a
map[add](5)
fn main():
var c: Int = 0
fn add(a: Int, /) capturing:
c += a
map[add](5)
bunny
bunnyβ€’8mo ago
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.
No description
Jake Brooks
Jake Brooksβ€’8mo ago
Since the map function isn't part of the builtin module, you'll need to explicitly import it: from algorithm import map
ModularBot
ModularBotβ€’8mo ago
Congrats @Jake Brooks, you just advanced to level 1!
bunny
bunnyβ€’8mo ago
ty! For any other potential readers: https://docs.modular.com/mojo/stdlib/algorithm/functional Ty again, @Jake Brooks . 😊
benny
bennyβ€’8mo ago
@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 :)
bunny
bunnyβ€’8mo ago
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.
ModularBot
ModularBotβ€’8mo ago
Congrats @bunny, you just advanced to level 3!
seboll13
seboll13OPβ€’8mo ago
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 πŸ™‚
benny
bennyβ€’8mo ago
if you send the full code I can help, but likely SIMD will be the way to go
seboll13
seboll13OPβ€’8mo ago
I’ll understand how it works then and get back to you if needed:)
Want results from more Discord servers?
Add your server