如何访问向量 clojure 向量中的特定元素 [英] How do I access a specific element in a vector of vectors clojure

查看:27
本文介绍了如何访问向量 clojure 向量中的特定元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个向量定义为

If I have a vector defined as

(def matrix [[1 2 3][4 5 6]])

我如何在 clojure 中访问向量向量中的随机元素?我一直在网上看到人们说在列表上使用向量的好处之一是您可以获得随机访问,而不必通过列表递归,但我一直无法找到允许我这样做的函数.我习惯于在 c++ 中我可以做 matrix[1][1] 并且它会返回第二个向量的第二个元素.

How in clojure do I access a random element in a vector of vectors? I keep seeing people say online that one of the benefits to using a vector over a list is that you get random access instead of having to recurse through a list but I haven't been able to find the function that allows me to do this. I'm used to in c++ where I could do matrix[1][1] and it would return the second element of the second vector.

我是不是必须一次循环一个元素通过我的向量,还是有更简单的方法来访问特定元素?

Am I stuck having to loop one element at a time through my vector or is there an easier way to access specific elements?

推荐答案

几乎就像你在 C++ 中所做的一样:

Almost like you would do it in C++:

user=> (def matrix [[1 2 3][4 5 6]])
user=> (matrix 1)
[4 5 6]
user=> ((matrix 1) 1)
5

正如文档所说:

向量实现了 IFn,用于一个参数的 invoke(),它们假定它是一个索引并在自身中进行查找,就像按第 n 个一样,即向量是其索引的函数.

Vectors implement IFn, for invoke() of one argument, which they presume is an index and look up in themselves as if by nth, i.e. vectors are functions of their indices.

这篇关于如何访问向量 clojure 向量中的特定元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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