Kev*_*ker 2 dictionary clojure
我正在写一个小小的"秘密圣诞老人"程序,让我的手弄脏了Clojure,而且我对我的输出感到磕磕绊绊.
该程序采用一组集(圣诞老人),将他们的电子邮件提取到另一个列表,然后随机将收件人分配给圣诞老人.我想我已经得到了它,但当我尝试输出我的结果时map,我得到了#<Fn@dc32d15 clojure.core/map$fn__4549>,
(ns secret-santas-helper.core
(:require [clojure.pprint :as pprint])
(:gen-class))
(def santas [{:name "Foo" :email "foo@gmail.com"}
{:name "Bar" :email "bar@gmail.com"}
{:name "Baz" :email "baz@gmail.com"}])
(defn pluck
"Pull out the value of a given key from a seq"
[arr k]
(map #(get % k) arr))
(defn find-first
"Find the first matching value"
[f coll]
(first (filter f coll)))
(defn assign-santas
"Iterate over a list of santas and assign a recipient"
[recipients santas]
(let [r (atom recipients)])
(map (fn [santa]
(let [recipient (find-first #(= % (get santa :email)) @recipients)]
(assoc santa :recipient recipient)
(swap! recipients (remove #(= % recipient) recipients))))))
(defn -main []
(let [recipients (shuffle (pluck santas :email))
pairs (assign-santas recipients santas)]
(pprint/pprint pairs)))
Run Code Online (Sandbox Code Playgroud)
还要注意你的使用方法map.你要归还你的结果swap!,我不相信你的目标.
继续努力让您的版本正确编译和运行.我想为你的问题提供一个替代解决方案,它可以减少变异,而是专注于组合集合.
(def rand-santas
"Randomize the current santa list"
(shuffle santas))
(def paired-santas
"Use partition with overlap to pair up all random santas"
(partition 2 1 rand-santas))
(def final-pairs
"Add the first in the list as santa to the last to ensure everyone is paired"
(conj paired-santas (list (last rand-santas) (first rand-santas))))
(defn inject-santas
"Loop through all pairs and assoc the second pair into first as the secret santa"
[pairs]
(map
(fn [[recipent santa]]
(assoc recipent :santa santa))
pairs))
(defn -main []
(pprint/pprint (inject-santas final-pairs)))
Run Code Online (Sandbox Code Playgroud)