问题描述
我想知道,如果我缺少一些基本涉及矢量操纵。让我们假设我有以下:
I am wondering if I'm missing something basic involving vector manipulation. Let's say I have the following:
(def xs [9 10 11 12 13])
(def idx [0 2])
(def values [1 3])
在Matlab中的向量 [1 10 3 12 13]
,我会写 xs(idx)= values
。
在Clojure中,有没有一个原始的方法来实现这个?现在我使用以下函数:
If I want to return the vector [1 10 3 12 13]
in Matlab, I would write xs(idx) = values
.In Clojure, is there a primitive way of achieving this? Right now I'm using the following function:
(defn xinto [seq idx val]
(apply assoc seq (interleave idx val)))
谢谢。
推荐答案
这有点尴尬,因为你分开了 idx
和值
分成两个序列,当它们在概念上是索引到值的映射。所以,如果你允许我对你的数据格式进行一些创造性的修改:
It's a bit awkward because you've split up idx
and values
into two seqs, when they're conceptually a map of indexes to values. So if you'll permit me a little creative modification of your data format:
(def x [9 10 11 12 13])
(def changes {0 1, 2 3})
(defn xinto [v changes]
(reduce (fn [acc [k v]]
(assoc acc k v))
v
changes))
(xinto x changes) ;; gets the result you want
如果生成 idx
and values
以一些奇怪的方式,将它们组合在一起不方便,可以稍后用(映射列表idx值)
然后使用 xinto
实现。
If you generate idx
and values
in some weird way that it's not convenient to group them together, you can group them later with (map list idx values)
and then use my xinto
implementation with that.
这篇关于如何在Clojure中修改矢量的一部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!