关于Clojure中reduce函数片段(inc (%1 %2 0))的技术咨询
(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)):
%1and%2: These are shorthand parameters in the anonymous function passed toreduce.%1is the accumulator map—the map we're building up that tracks word counts so far.%2is the current word being processed from the sequence generated byre-seq.
(%1 %2 0): In Clojure, maps act like functions that look up keys. Normally,(%1 %2)would return the count of word%2if it's already in the map, ornilif it's not. The third argument0is a default value—so if the word isn't in the map yet, it returns0instead ofnil.inc: This is a simple function that adds 1 to its argument. So when we wrap(%1 %2 0)withinc, we're:- If the word is new: taking the default
0and turning it into1(since it's the first occurrence). - If the word exists: taking its current count (say, 3) and turning it into
4(incrementing the count).
- If the word is new: taking the default
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

