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

关于Clojure中reduce函数片段(inc (%1 %2 0))的技术咨询

Understanding (inc (%1 %2 0)) in the Word Frequency Reduce Function

Hey there! Let's break down that specific piece of code you're confused about—no jargon, just plain explanations:

First, let's recap the context of where this lives:

(reduce #(assoc %1 %2 (inc (%1 %2 0))) {} (re-seq #"\w+" s))

This is a manual way to build a word frequency map. Let's zoom in on (inc (%1 %2 0)):

  • %1 and %2: These are shorthand parameters in the anonymous function passed to reduce.

    • %1 is the accumulator map—the map we're building up that tracks word counts so far.
    • %2 is the current word being processed from the sequence generated by re-seq.
  • (%1 %2 0): In Clojure, maps act like functions that look up keys. Normally, (%1 %2) would return the count of word %2 if it's already in the map, or nil if it's not. The third argument 0 is a default value—so if the word isn't in the map yet, it returns 0 instead of nil.

  • inc: This is a simple function that adds 1 to its argument. So when we wrap (%1 %2 0) with inc, we're:

    • If the word is new: taking the default 0 and turning it into 1 (since it's the first occurrence).
    • If the word exists: taking its current count (say, 3) and turning it into 4 (incrementing the count).

Putting it all together: (inc (%1 %2 0)) calculates the new count for the current word, which then gets stored back into the accumulator map via assoc.

And as the comment mentions, this entire reduce expression does the exact same thing as the built-in frequencies function—so you could replace the whole thing with (frequencies (re-seq #"\w+" s)) and get the same result!

内容的提问来源于stack exchange,提问作者nenad

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:58:21