Ruby及JS中reduce方法参数顺序的设计缘由探究
reduce Great question! This isn’t a random choice at all—there are solid design reasons behind putting the accumulator as the first parameter in both Ruby’s reduce (and its alias inject) and JavaScript’s reduce. Here’s a breakdown of the key considerations:
Readability that aligns with natural thinking
When you write areduceblock like{ |sum, n| sum + n }, it reads like a natural statement: "Take the current sum, add the next number n to it". This matches how most people mentally model accumulation—you start with a running total, then update it with each new element. If the order were reversed ({ |n, sum| sum + n }), the flow feels less intuitive, even though the logic works.Alignment with functional programming traditions
Both Ruby and JavaScript drew inspiration from functional programming languages (like Lisp, which popularized thereduce/foldpattern). In these languages, the accumulator-first order is standard. By following this convention, the languages made it easier for developers familiar with functional paradigms to transition smoothly, while also establishing a consistent pattern across the broader programming ecosystem.Better fit for common use cases
Mostreduceoperations involve modifying the accumulator (building a hash, appending to an array, calculating a running total). Putting the accumulator first makes these operations more straightforward. For example, when building a hash from an array:["apple", "banana", "cherry"].reduce({}) do |fruit_map, fruit| fruit_map[fruit] = fruit.length fruit_map endHere, you immediately have access to the accumulator (
fruit_map) to update it, which feels more logical than reaching for it after the current element.
JavaScript’s reduce follows the same logic—this shared parameter order isn’t a coincidence. It’s a deliberate choice to prioritize readability, consistency with existing paradigms, and ease of use for the most common reduce scenarios.
内容的提问来源于stack exchange,提问作者spike

