简体   繁体   English

在Clojure的集合中查找最长字符串的长度

[英]Find Length of Longest String in a Collection in Clojure

This seems like it should be comically easy but I somehow can't figure it out: how do you find the length of the longest string in a collection in Clojure? 这看起来似乎应该很容易上手,但是我却无法弄清楚:如何在Clojure的集合中找到最长字符串的长度?

eg (fn ["cat", "dog", "bear"]) => 4 例如(fn ["cat", "dog", "bear"]) => 4

user=> ((fn [strs] (apply max (map count strs))) ["cat" "dog" "bear"])
4

(max (count coll)) is counting the collection, which returns 3, and then taking the max of 3 (and nothing) results in 3. This is not what you want. (max (count coll))对集合进行计数,该集合将返回3,然后取max 3(而不是max )将得出3。这不是您想要的。

(apply max count coll) results in (max count "cat" "dog" "bear") which leads to comparing a symbol and strings with max , and that throws an exception because max expects one or more numbers. (apply max count coll)导致(max count "cat" "dog" "bear")导致将符号和字符串与max进行比较,并抛出异常,因为max需要一个或多个数字。

(fn ["cat", "dog", "bear"]) is not valid syntax and results in an exception that fn does not conform to the spec. (fn ["cat", "dog", "bear"])是无效的语法,并导致fn不符合规范的异常。 The special form fn takes as first argument a vector of symbols (binding-form) (or optionally the name and than third argument the binding-form) . 特殊形式fn将符号向量(绑定形式)(或者可选地将名称作为名称向量,将第三个参数作为绑定形式)作为第一个参数。 Eg, (fn ident [n] n)) is a function with the name ident that takes an argument n and returns n , ((fn [n] n) 1) ;; => 1 例如, (fn ident [n] n))是具有名称ident的函数,该函数接受参数n并返回n ((fn [n] n) 1) ;; => 1 ((fn [n] n) 1) ;; => 1 . ((fn [n] n) 1) ;; => 1

So taking these things in mind, one approach is to first determine the counts of the elements in the coll and then finding the max of that coll. 因此,请记住这些事情,一种方法是首先确定coll元素的数量,然后找到该coll的max

(def coll ["cat" "dog" "bear"]) (or use a set #{"cat" "dog" "bear"} if you don't need duplicates) (def coll ["cat" "dog" "bear"]) (或如果不需要重复项,请使用一组#{"cat" "dog" "bear"}

Here are a few ways to do so: 这里有几种方法:

(apply max (map count coll)) ;; => 4 (apply max (map count coll)) ;; => 4 turn the collection in collection of counts [3 3 4] and apply max to get (max 3 3 4) . (apply max (map count coll)) ;; => 4将集合转换为计数[3 3 4]apply max以获得(max 3 3 4)

(reduce max (map count coll)) ;; => 4 (reduce max (map count coll)) ;; => 4 Same as above but reduce the collection by taking max of first element only, then second element with max of previous result, and so on. (reduce max (map count coll)) ;; => 4与上面相同,但是通过仅取第一个元素的max ,然后取第二个元素的先前结果的max ,以减少收集,依此类推。

And depending on what you need you can do things like: 根据您的需要,您可以执行以下操作:

(group-by count coll) ;; => {3 ["cat" "dog"], 4 ["bear"]}

(sort-by count ["a" "aa" "aaa" "aa" "aaaaa" "a"]) ;; => ("a" "a" "aa" "aa" "aaa" "aaaaa")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM