[英]Only map a set of specified values in Clojure
我已經和這個小小的Clojure片段進行了一段時間的摔跤,但一直覺得有更慣用,更簡單的方法。
期望的行為; 轉換“1” - > true,“0” - > false。 否則按原樣返回參數:
(= (mapper {:column 0} ["monkey" "stuff"]) "monkey")
(= (mapper {:column 0} ["1" "stuff"]) true)
(= (mapper {:column 0} ["0" "stuff"]) false)
這是我的第一次嘗試; 一種天真的命令式方法:
(defn mapper
[attr-map row]
(let [x (row (:column attr-map))
y ({"1" true "0" false} x)]
(if (nil? y)
x
y)))
第二次嘗試:
(defn mapper
[attr-map row]
((comp #({"1" true "0" false} % %) row :column) attr-map))
有人能找到更好的解決方案嗎?
如果:column
鍵是標准鍵,則可以使用解構 。
(defn mapper [{c :column :or {c 0}}
{item c}]
({"1" true "0" false} item item))
({"1" true "0" false} item item)
可以將Hashmaps視為函數,其第一個參數是鍵,以檢索值。 此表單還接受第二個可選參數,該參數在hashmap不包含密鑰時返回。
{c :column :or {c 0}}
這個解構形式使用:column
作為傳入函數第一個參數的項的鍵。 (在這種情況下,這是您的{:column 0}
hashmap。)可選:or
關鍵字允許在:column
鍵不存在時使用默認值,或者參數不是有效集合(例如,nil,數字,日期,等等)。 c
現在將包含:column
鍵的值或默認值0。
{item c}
由於作為第二個參數傳遞的集合是可索引的,因此您可以使用先前使用的相同表單。 在前一個解構形式c
命名的var包含值:column
,它可以用於索引到第二個參數,並將結果值賦給item
。
如果可以保證輸入參數格式,可以進一步簡化為:
(fn [{i :column} {x i}] ({"1" true "0" false} x x))
我會尋求更長時間(更可讀?)的實現:
(defn mapper [{c :column} row]
(let [v (row c)]
(condp = v
"1" true
"0" false
v)))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.