Proposal: Better lossy casting for int-to-float

I used to find this annoying as well, but now I see @as(f32, @floatFromInt(n)) as a code smell. It usually indicates you’re doing too much in a single assignment statement.

const ratio: f32 = @as(f32, @floatFromInt(i)) / @as(f32, @floatFromInt(sin_d.len - scale));                                                                                                                              

Should be broken up into:

const loop_index: f32 = @floatFromInt(i);                               
const div: f32 = @floatFromInt(sin_d.len - scale);                      
const ratio: f32 = loop_index / div;                                                                                                                                          

This makes the exact order in which the mathematical operations & typecasts happen clear and unambiguous. You can also give the variables descriptive names, or add comments next to each line individually.

A more in-depth example: Bm25er - Search local files like you're searching the web (BM25 implementation) - #3 by vincentd

1 Like