‹ BackHN Continuity

Thread

Anecdotally, programmers dislike "reduce"

175 points · 283 comments · vinhnx

  1. xdavidliu · · focus · HN ↗
    reduce has complexity to handle the edge case of an empty iterable, and also for the case of a binary function with different types for inputs and outputs. That makes it harder to reason about and "uglier" than map and filter. People probably hate sum and product significantly less, both those also have the edge cases of empty iterable, in which case the natural result is 0 for sum and 1 for product sure, but of what type?

    While we're on the subject, can someone explain to me why in Rust, you need to annotate the type when you call .sum() on an iterable? For example

        let p: i32 = [1i32, 2, 3].iter().sum();
        println!("hello {}", p);
    
    That works, but fails if I replace `p: i32` with `p` or `p: i64`, and I cannot find a satisfactory answer in any thread or llm. The obvious question is why the compiler cannot infer the type from the element type of the container, and the naive response to that is for flexibility summing into a bigger type. But in that case, why would `p: i64` be rejected? And what other type is allowed besides i32?
Open on Hacker News to reply ↗

Unofficial Hacker News client; not affiliated with Y Combinator.