为了好玩,我使用 Peter Norvig 的 Udacity CS212 课程(用 python 授课)作为学习 Clojure 的工具。
在所述课程中,他有一个函数可以返回以指定频率出现的序列的第一个元素:
def kind(n, ranks):
"""Return the first rank that this hand has
exactly n-of-a-kind of. Return None if there
is no n-of-a-kind in the hand."""
for r in ranks:
if ranks.count(r) == n: return r
return None
我已经想出了如何在 clojure 中作为单行来做到这一点,但它是多么可怕的单行:
(defn n-of-kind
[n ranks]
"Detect whether a hand rank contains n of a kind, returning first
rank that contains exactly n elements"
(first (keys (into {} (filter #(= (second %) n) (frequencies ranks))))))
(n-of-kind 3 [5 5 5 3 3]) ;; correctly returns 5
我的直觉是必须有更好的方法。频率函数非常有用,但此代码的其余部分只是搜索一个值并返回其键。如果频率函数返回了一个以频率作为键而不是值的映射,我可以执行类似 ((frequencies ranks) n) 的操作。
任何人都可以提出一种更易读/更简洁的方法吗?