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

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

问题描述

如果我有一个向量定义为

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

如何在clojure中访问向量的向量中的随机元素?我不断地看到人们在网上说,使用向量在列表上的好处之一是你获得随机访问,而不是通过列表递归,但我还没有能够找到允许我这样做的功能。我习惯于在c + +其中我可以做矩阵[1] [1],它会返回第二个向量的第二个元素。



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

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

由于 docs说


向量实现IFn,用于调用一个参数的invoke(),他们假定它是一个索引并且自己就像是通过nth查找,即向量是它们的索引的函数。



If I have a vector defined as

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

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?

解决方案

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

As the docs say:

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天全站免登陆