如何在Clojure中统计数组内的Map数量?附示例验证
Hey there! Let's break down how to solve this problem with your example in mind.
First, let's recall your sample input: [{:a "a"} {:b "b"}] — you want to get the count of Map entries here, which should be 2.
Method 1: Filter + Count
The most straightforward approach is to use filter to keep only elements that are Maps, then use count to tally them up. Clojure has a built-in predicate map? that checks if an element is a Map type.
Here's the code:
(count (filter map? [{:a "a"} {:b "b"}]))
When you run this, it'll return 2 exactly as you expected. Let's break it down:
map?checks each element in the collection to see if it's a Mapfiltercreates a new sequence containing only elements wheremap?returns truecountthen counts how many elements are in that filtered sequence
Method 2: Reduce for Manual Accumulation
If you prefer a more explicit approach, you can use reduce to iterate through the collection and increment a counter each time you encounter a Map:
(reduce (fn [acc elem] (if (map? elem) (inc acc) acc)) 0 [{:a "a"} {:b "b"}])
This works by initializing the counter (acc) to 0, then for each element:
- If it's a Map, increment the counter
- Otherwise, keep the counter the same
At the end, you'll have the total count of Maps.
Bonus: Handling Mixed Collections
Both methods work even if your collection has other types of elements. For example, if you have [{:a 1} "test" 42 {:b 2}], running either of the above code snippets will return 2, correctly ignoring the string and number.
内容的提问来源于stack exchange,提问作者THX1137

