“更新”在Clojure中的连续函数调用中的映射/数据结构 [英] "Updating" a map/data structure in consecutive function calls in Clojure

查看:104
本文介绍了“更新”在Clojure中的连续函数调用中的映射/数据结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Clojure中通过多次函数调用来更新地图。该想法表示如下:

 (defn foo1 
[a-map]
(assoc a -map:key1value1))

(defn foo2
[a-map]
(assoc a-map:key2value2))

(defn foo3
[a-map]
(assoc a-map:key3value3))

(defn -main
[]
(let [a-map {}]
(do(foo1 a-map)
(foo2 a-map)
(foo3 a-map)
a- map)))

显然这段代码是错误的,因为 em>不在子程序的范围之外更新。它是这样写的,因为它比我目前的正确实现更清晰。预期结果为:

  {:key1value1:key2value2:key3value3} 

我的问题是,什么是最好的方式来完成任务的clojure方式。

我已经考虑嵌套几个 let 表达式,其中每个 let 可以保存更新后的 a-map 。我还考虑使用 loop-recur 结构,其中 a-map 作为绑定传递。



干杯





EDIT :为问题添加约束。函数 foo1,foo2,foo3 实际上比只有 a-map 需要更多的参数。其中一些参数只能通过处理传递给 -main 的参数来确定。

解决方案

assoc 返回更新的地图,以便您可以使用 - > 线程宏:

 (let [a-map( - > {} 
foo1
foo2
foo3)] ...)

或者您可以使用 code>:

 (let [a-map((comp foo3 foo2 foo1){})] ... )


I want to "update" a map through multiple calls of functions, in Clojure. The idea is expressed as below:

(defn foo1
  [a-map]
  (assoc a-map :key1 "value1"))

(defn foo2
  [a-map]
  (assoc a-map :key2 "value2"))

(defn foo3
  [a-map]
  (assoc a-map :key3 "value3"))

(defn -main
  []
  (let [a-map {}]
    (do (foo1 a-map)
        (foo2 a-map)
        (foo3 a-map)
        a-map)))

Apparently this piece of code is wrong because the a-map is not updated outside the scope of subroutines. It's written like this simply because it's clearer as compared to my current "correct" implementation. The expected result is:

{:key1 "value1" :key2 "value2" :key3 "value3"}

My question is, what is the best way to fulfil the task in the clojure way.

I have considered nesting a few let expressions where each let can hold the result of the updated a-map. I also considered using a loop-recur structure where the a-map is passed as a binding. But both approaches look untidy.

Any advice would be appreciated.

Cheers

EDIT: Adding a constraint to the question. The functions foo1, foo2, foo3 actually takes more parameters than only the a-map. And some of these parameters can only be determined by processing the arguments passed to -main.

解决方案

assoc returns the updated map so you can chain your calls using the -> threading macro:

(let [a-map (-> {} 
                foo1
                foo2
                foo3)] ...)

or you could use comp:

(let [a-map ((comp foo3 foo2 foo1) {})]...)

这篇关于“更新”在Clojure中的连续函数调用中的映射/数据结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆