gpt4 book ai didi

clojure - 将转换应用于数据映射的正确方法?

转载 作者:行者123 更新时间:2023-12-02 12:20:03 25 4
gpt4 key购买 nike

我正在尝试想出一种将特定转换函数应用于数据 map 的好方法。

以 map 为例:

{:wrapper {:firstName "foo" 
:lastName "bar"
:addressLine1 "line1"
:addressLine2 "line2"
:birthDate {:iso "1930-03-12"}}}

并将其转换为:

{:name "foo bar"
:address "line1 /n line2"
:age 86}

我也希望转换以相反的方式工作,尽管我不介意编写单独的转换。

到目前为止,我已经尝试编写转换函数列表:(伪)

(-> start-map
transform-name
transform-address
transform-age)

每个变换都采用[start-map {accumulator-map}]。我还尝试编写一个映射,其中包含转换后的映射的键以及转换函数(和参数)作为它们的值。我觉得我错过了一个技巧。

最佳答案

变换:

(require '[clj-time.core :as t])
(require '[clj-time.format :as f])

(def data {:wrapper {:firstName "foo"
:lastName "bar"
:addressLine1 "line1"
:addressLine2 "line2"
:birthDate {:iso "1930-03-12"}}})

(def transformed
{:name (str (get-in data [:wrapper :firstName])
" "
(get-in data [:wrapper :lastName]))
:address (str (get-in data [:wrapper :addressLine1])
"\n"
(get-in data [:wrapper :addressLine2]))
:age (t/in-years (t/interval (f/parse
(get-in data [:wrapper :birthDate :iso] data))
(t/now)))})

逆变换。请注意,日期失去了精度。

(require '[clojure.string :as str])

(def untransformed
(let [[firstname lastname] (str/split
(:name transformed)
#" ")
[addressline1 addressline2] (str/split
(:address transformed)
#"\n")]
{:wrapper
{:firstName firstname
:lastName lastname
:addressLine1 addressline1
:addressLine2 addressline2
:birthDate
{:iso (f/unparse
(f/formatters :date)
(t/minus (t/now)
(t/years (:age transformed))))}}}))

关于clojure - 将转换应用于数据映射的正确方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40165463/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com