대안

2011-10-29 5 views
2

나는지도에 중첩 된지도 (실제로 데이터를 트윗)와 목록을 변환하려면 다음 작업 코드를 가지고, 내가 예상대로였다 작품이 비록대안

(defn filter 
    "This function returns a map with the user as key, #followers as value" 
    [raw-tweets] 

    (let [users (map :user raw-tweets) 
     names (map :name users) 
     followers (map :followers_count users)] 
    (zipmap names followers))) 

을 Clojure에서 이것을 수행하는 데 더 관용적 인 방법이 있을지 궁금해한다. 어떤 대안?

답변

2

은 괜찮 :

 
(defn user-followers [raw-tweets] 
    (reduce #(assoc %1 (:name %2) (:followers_count %2)) 
    {} (map :user raw-tweets))) 
+0

친절하고 깨끗한. 감사 –

1

나는 clojure를 배우기 시작했으나이 방법은 좀 더 관용적이라고 생각합니다. 어쨌든 대안입니다.

(defn filter 
    "This function returns a map with the user as key, #followers as value" 
    [raw-tweets] 
    (into {} (map #(let [user (:user %)] 
        [(:name user) (:followers_count user)]) 
       raw-tweets))) 

그것은 각각의 트윗에 대한 사용자를 검색하고 이름을 가진 벡터를 반환하고 추종자가 해당 사용자에 대해 계산하는 기능을 가진 원료 트윗을 통해 매핑합니다. into 함수는 두 개의 시퀀스를 취하여 두 번째 요소의 모든 요소를 ​​첫 번째 요소로 결합합니다. 그러면 벡터 함수가 필터 함수에서 반환되기 전에 벡터 목록이지도로 바뀝니다.

1

@ Daan의 답변이 멋지지만 믹스에 파괴가 추가됩니다. 당신이 감소하여가는대로지도를 구축 할 수 있지만 당신은 무엇

(defn filter-tweets 
    "This function returns a map with the user as key, #followers as value" 
    [raw-tweets] 
    (into {} (map (fn [{{name :name follower-count :followers_count} :user}] 
        [name follower-count]) 
       raw-tweets))) 
1

내가 (map (fn ...)) 패턴을 좋아하지 않는다 - 정말 쓰기 단지 추한 방법 for 이해력. 좀 덜 자연 나에게 느낌이 있지만, 그냥 어쨌든 한 번 사용하려고하고 값에 대한 이름을 발명 방지

(into {} 
     (for [{:keys [user]} raw-tweets] 
     ((juxt :name :followers_count) user))) 

또는이 : 나는대로이 쓰기 것입니다.

(into {} (map (comp (juxt :name :followers_count) :user) 
       raw-tweets))