我试图从 clojuredocs.org 理解这个函数:
;; Create a word frequency map out of a large string s.
;; `s` is a long string containing a lot of words :)
(reduce #(assoc %1 %2 (inc (%1 %2 0)))
{}
(re-seq #"\w+" s))
; (This can also be done using the `frequencies` function.)
Run Code Online (Sandbox Code Playgroud)
我不明白这部分: (inc (%1 %2 0))
%1传递给函数的第一个参数(在匿名函数中)reduce是累加器,它最初是{}作为第二个参数传递给 的空映射reduce。映射是查找给定键的值的函数,如果找不到键,则返回可选的默认值,例如
({"word" 1} "word") = 1
Run Code Online (Sandbox Code Playgroud)
和
({"word" 1} "other" 0) = 0
Run Code Online (Sandbox Code Playgroud)
所以
(%1 %2 0)
Run Code Online (Sandbox Code Playgroud)
在累加器映射中查找当前单词(reduce 函数的第二个参数)的计数,如果尚未添加单词,则返回 0。inc增加当前计数,所以
#(assoc %1 %2 (inc (%1 %2 0))
Run Code Online (Sandbox Code Playgroud)
增加中间映射中当前单词的计数,如果这是第一次遇到该单词,则将其设置为 1。
| 归档时间: |
|
| 查看次数: |
897 次 |
| 最近记录: |