You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ruby及JS中reduce方法参数顺序的设计缘由探究

Why Ruby (and JavaScript) Put the Accumulator First in 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 a reduce block 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 the reduce/fold pattern). 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
    Most reduce operations 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
    end
    

    Here, 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:28:44